基本工具
1.使用和避免 null
在项目中常常需要判断非空的问题
Guava工具类为我们提供了一下校验对象相关的工具类
Preconditions类
Long age = 18L;
//校验参数是否为null
Preconditions.checkNotNull(age, "age不能为null");
//校验参数是否满足条件,并打印出来参数信息,后期可查看日志方便追溯问题
Preconditions.checkArgument(age < 0, "age: %s必须大于0", age);
//校验list是否为null
List<String> list = Lists.newArrayList();
//校验参数是否为null
Preconditions.checkNotNull(list, "传入的list不能为null");
//校验参数index是否在该集合里,元素索引的范围可以是零
Preconditions.checkElementIndex(index, size);
ps:小建议 在编码时,建议把多个条件放到不同行,这样可方便查看与调试
##2.常见 Object 方法
###2.1 equals
当一个对象中的字段可以为 null 时,实现 Object.equals 方法会很痛苦,因为不得不分别对它们进行 null 检
查。使用Objects.equal 帮助你执行 null 敏感的 equals 判断,从而避免抛出 NullPointerException。例如:
Objects.equal("li", "li"); // returns true
Objects.equal(null, "li"); // returns false
Objects.equal("li", null); // returns false
Objects.equal(null, null); // returns true
2.2 hashCode
UserInfoEntity userOne = new UserInfoEntity(null, (byte) 0);
UserInfoEntity userTwo = new UserInfoEntity(null, (byte)0);
int hashCodeOne = Objects.hashCode(userOne);
nt hashCodeTwo = Objects.hashCode(userOne);
class UserInfoEntity {
private String name;
private byte age;
public UserInfoEntity(String name, byte age) {
this.name = name;
this.age = age;
}
}
结果
toString
String s = Objects.toStringHelper(userOne).add("name","li").add("add","北京").toString();
System.out.println(s);
结果 UserInfoEntity{name=li, add=北京}