同一父類,不同子類集合可判斷該元素組是否相等
判斷集合是否相等時只關注元素是否相等,無需考慮型別,即同調父類AbstractList裡的equal方法
原始碼如下:
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
AbstractSet和AbstractMap等集合父類也是一樣,若該子類呼叫equal方法,無須分子類集合型別,僅考慮元素是否相等
原始碼如下:
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;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection<?> c = (Collection<?>) o;
if (c.size() != size())
return false;
try {
return containsAll(c);
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
}
測試程式碼用例
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
public class Test49
{
public static void main(String[] args)
throws Exception
{
List<String> strs = new ArrayList<>();
strs.add("A");
List<String> strs2 = new Vector<>();
strs2.add("A");
Map<String, String> strs3 = new HashMap<>();
strs3.put("1", "A");
Map<String, String> strs4 = new Hashtable<>();
strs4.put("1", "A");
Set<String> strs5 = new HashSet<>();
strs5.add("A");
Set<String> strs6 = new TreeSet<>();
strs6.add("A");
System.out.println(strs.equals(strs2));
System.out.println(strs3.equals(strs4));
System.out.println(strs5.equals(strs6));
}
}
執行結果:
true
true
true
參照來源:《編寫高質量程式碼:改善java程式的151建議》 <