思路
首先,判断是否为同一对象(this==anObject);
其次,判断是否为同一类型(instanceof);
第三,判断长度是否相等;
最后,判断具体内容是否相等。
Object
public boolean equals(Object obj) {
return (this == obj);
}
String
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
HashMap
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<?,?> m = (Map<?,?>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
数组(只判断是否为同一对象,较特殊)
int[] a=new int[2];
int[] b=new int[2];
a[0]=b[0]=1;
a[1]=b[1]=2;
System.out.println(a.equals(a));//true
System.out.println(a.equals(b));//false