AbstractSet源碼__iterator

來源:互聯網
上載者:User

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尋找,遍曆誰都一樣了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.