源码
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++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
String类型
ArrayList<Integer> names = new ArrayList<Integer>();
names.add("Jim");
System.out.println(names.contains("Jim"));
分析:names先调用contains方法,然后o调用indexOf方法,之后执行else后代码块内容,一个个数据作对比,发现相同才返回true
包装类
ArrayList<Integer> ages = new ArrayList<Integer>();
ages.add(12);
System.out.println(ages.contains(new Integer(12)));
分析:基本数据类型包装类,则contains方法实质上调用的是包装类中的equals。
o是12,调用Integer中的equals,它是比较值是否相等
自定义类类型:
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("111"));
System.out.println(students.contains(new Student("111")));
分析:contains方法实质上调用的是类类型中的equals,需要重写equals
重写前:调用的是Object类equals
重写后:执行的是自定义类中的equals
instanceof
ArrayList<Object> list = new ArrayList<Object>();
list.add(new String("111"));
System.out.println(list.contains(new Student("111")));
分析:如果不用instanceof,会有异常,obj是一个字符串,不能强制类型转换学生,所以出异常,所以需要这样重写equals
public boolean equals(Object obj){
if(obj instanceof Student){
Student s = (Student)obj;
String argId = this.id;
String elementId = s.id;
return argId.equals(elementId);
}
return false
}