Java的List.contains()用于检查元素是否存在于列表中,如果存在则返回true,否则返回false.
一、List.contains()方法的基本使用 {#title-1}
contains()方法:需将需要检查的元素作为参数传递进去,然后调用List对象的contains()方法.
Listlist = new ArrayList();
list.add("Java");
list.add("Python");
list.add("JavaScript");
boolean result = list.contains("Java"); // true
二、List.contains()方法的内部实现 {#title-2}
List.contains()方法的内部实现依赖于List中元素类型的equals()方法. 如果List中元素类型没有重写equals()方法,可能导致contains()出现错误.
class MyObject {
private int id;
public MyObject(int id) {
this.id = id;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
MyObject myObject = (MyObject) other;
return id == myObject.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
MyObject obj1 = new MyObject(1);
MyObject obj2 = new MyObject(2);
MyObject obj3 = new MyObject(1);
Listlist = new ArrayList<>();
list.add(obj1);
list.add(obj2);
System.out.println(list.contains(obj3)); // true
三、List.contains()方法的性能 {#title-3}
List.contains()方法在执行时需要遍历整个数组来查找指定元素,因此它的时间复杂度是O(n)。如果在大数据量的使用中,性能可能下降明显.
ListlargeList = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
largeList.add("Number" + i);
}
long startTime = System.currentTimeMillis();
boolean result = largeList.contains("Number999999"); // true
long endTime = System.currentTimeMillis();
System.out.println("Total execution time: " + (endTime-startTime) + "ms");