Understanding of hashcode and equals

Source: Internet
Author: User

The two objects with the same attribute values are put into the list and set

Set set:

The equals and hashcode of the two objects are considered to be the same object;

If equals is false, set size is 2 regardless of the hashcode result;

If equals is true, the size is 1 only when hashcode is equal.

To make the two objects equal, you must rewrite equals and hashcode at the same time.

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

Summary:

1. The equals method is used to compare whether the content of an object is equal (after overwriting)

2. The hashcode method is only used in the set.

3. When the equals method is overwritten, the comparison object will be compared through the overwritten equals method (to determine whether the object content is equal ).

4. When an object is put into a set, first determine whether the hashcode value of the object to be put is equal to the hashcode value of any element in the set. If not, directly add the object to the set. If the hashcode value is equal, and then the equals method is used to determine whether the object to be put is equal to any object in the set. If equals judges that it is not equal, the element is directly put into the set, otherwise, do not place it.

5. flowchart for placing elements in a set:

6. source code of the add method in hashset:

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

Map. Put source code:

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;              }          }




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.