hashcode和equals的理解

來源:互聯網
上載者:User

標籤:style   blog   http   java   os   for   ar   2014   

屬性值相等的兩個對象,分別放進List和Set

Set集合:

兩個對象的equals和hashcode都相等,才認為是同一個對象;

如果equals為false,則不管hashcode什麼結果,Set size為2;

如果equals為true,只有當hashcode也相等,size才為1

所以要使得兩個對象相等,必須同時重寫equals和hashcode。

http://blog.csdn.net/afgasdg/article/details/6889383

總結:

1、equals方法用於比較對象的內容是否相等(覆蓋以後)

2、hashcode方法只有在集合中用到

3、當覆蓋了equals方法時,比較對象是否相等將通過覆蓋後的equals方法進行比較(判斷對象的內容是否相等)。

4、將對象放入到集合中時,首先判斷要放入對象的hashcode值與集合中的任意一個元素的hashcode值是否相等,如果不相等直接將該對象放入集合中。如果hashcode值相等,然後再通過equals方法判斷要放入對象與集合中的任意一個對象是否相等,如果equals判斷不相等,直接將該元素放入到集合中,否則不放入。

5、將元素放入集合的流程圖:

6、HashSet中add方法原始碼:

public boolean add(E e) {      return map.put(e, PRESENT)==null;      }

map.put原始碼:

public V put(K key, V value) {          if (key == null)              return putForNullKey(value);          int hash = hash(key.hashCode());          int i = indexFor(hash, table.length);          for (Entry<K,V> e = table[i]; e != null; e = e.next) {              Object k;              if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {                  V oldValue = e.value;                  e.value = value;                  e.recordAccess(this);                  return oldValue;              }          }

  




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.