Java Collection架構中就是Set系列最簡單了,Set介面和Collection介面一樣,
AbstractSet同樣非常簡單,只有三個方法的實現,這裡一一列出。
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;
}
}
真是簡單,這裡基本上是直接調用containsAll方法,因為如果兩個Set的集合大小相同,一個包含
另一個的話,就一定相等,這裡捕捉了兩個系統異常,直接返回false。
public int hashCode() {
int h = 0;
Iterator i = iterator();
while (i.hasNext()) {
Object obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
更簡單了,所有元素的hashCode加起來。
public boolean removeAll(Collection c) {
boolean modified = false; if (size() > c.size()) {
for (Iterator i = c.iterator(); i.hasNext(); )
modified |= remove(i.next());
} else {
for (Iterator i = iterator(); i.hasNext(); ) {
if(c.contains(i.next())) {
i.remove();
modified = true;
}
}
}
return modified;
}
這裡總是遍曆較小的集合,如果c小於這個Set,就遍曆c,這裡調用remove方法,不過modified|=比較厲害,只要有一次刪除成功,modified就是true。如果c大於這個Set,就遍曆自己,如果在c中存在就刪除。
這樣處理可以提高效率:因為使用了hash尋找後,contains方法時間複雜度應該是常熟,所以挑較小的集合遍曆可以提高效率。如果contains不是hash尋找,遍曆誰都一樣了。