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