如何快速创建数组
1、通过Arrays.asList(“a”, “b”);
2、Stream.of(“a”).collect(Collectors.toList());
3、通过guava提供的方法,List list3 = Lists.newArrayList(“a”);
小坑
List.contains()问题
List<Integer> tailList = {"1", "3", "5", "7", "9"};
Long id = 123456789L;
// result = false ,因为id % 10 = 1L是一个Long对象,而tailList中都是Integer,虽然值相等,但是类型不同
boolean result = tailList.contains(id % 10);
源码:
ArrayList的contains方法:
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
// 判断相等是基于equals方法判断的
if (o.equals(elementData[i]))
return i;
}
return -1;
}
Integer的equals方法:
public boolean equals(Object obj) {
// 先判断类型是否相投
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}