public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
接下来我们创建一个ArrayList数组,然后去调用contains方法和indexOf方法。
ArrayList<String> al = new ArrayList<String>();
String s1 = new String("abc");
String s2 = new String("abc");
al.add(s1);
al.add(s2);
System.out.println(al.size());
System.out.println(al.indexOf(s2));
---------- 运行 ----------
2
0
输出完成 (耗时 0 秒) - 正常终止
我们想获得s2,看看indexOf的实现吧!
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++)
<span style="color:#ff6666;">if (o.equals(elementData[i]))</span>
return i;
}
return -1;
}
红色字又使用到String类的equals方法 ,所以导致的。