List<String> testList = new ArrayList<>(); testList.add("A"); testList.add("B"); testList.add("C"); String newStr = "A"; if (testList.contains(newStr)){ return"exist"; }else { return"no exist"; }
但对于自定义类型,直接使用contains方法不能达到预期效果:
1 2 3 4 5 6 7 8 9 10
List<User> testList = new ArrayList<>(); testList.add(new User(1,"A")); testList.add(new User(2,"B")); testList.add(new User(3,"C")); User newUser = new User(1,"A"); if (testList.contains(newUser)){ return"exist"; }else { return"no exist"; }
这种情况下,返回no exist。
观察List中contains方法源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicbooleancontains(Object o){ return indexOf(o) >= 0; } publicintindexOf(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++) if (o.equals(elementData[i])) return i; } return -1; }
if (map.containsKey(batchStationOilConcessionsFilter)){ // 记录index,后面删除 list.add(batchStationOilConcessionsDTO.getIndex()); }else{ map.put(batchStationOilConcessionsFilter, new Date()); }