1. 集合处理
1.1 remove() vs removeAll()
@Test
public void test() {
List<String> all = new ArrayList<>();
List<String> little = new ArrayList<>();
// List<String>' may not contain objects of type 'List<String>'
all.remove(little);
// 更正
all.removeAll(little);
}
2. 空指针
2.1 类型转换 Integer
@Data
public class User {
private Integer status;
private int bizStatus;
}
@Test
public void test() {
User user = new User();
// User(status=null, bizStatus=0)
if (user.getBizStatus() == 1) {}
// java.lang.NullPointerException
if (user.getStatus() == 1) {}
}
分析:
new User()
初始化时,基本类型会被复制,引用类型为null
优化:
方式一:Objects.equals()
if (Objects.equals(user.getStatus(), 1)) {}
方式二:声明常量
private static Integer STATUS = 1;
@Test
public void test() {
User user = new User();
if (STATUS.equals(user.getStatus())) {}
}
网友评论