If two objects have the same hash code, but not equal, can they exist simultaneously in the HashMap?

Source: Internet
Author: User

If two objects have the same hash code, but not equal, can they exist simultaneously in the HashMap?

----answer is yes.

Reason:

In HashMap, because key can not be duplicated, he judged the key is not repeated when the hashcode this method, but also used the Equals method.

It is not possible to repeat here that equals and hashcode as long as there is a range.

When we add an element to a set, HashMap, HashSet, Hashtable collection, the collection first calls the Hashcode method of the object,

This allows you to directly locate the location where it is stored, and if there are no other elements, save it directly.
If there is already an element there, call the Equals method to match whether the two elements are the same, the same is not present, and the difference is hashed to a different location

Second, hashcode important?
For a list collection, an array, he is a burden, not important, but for HashMap, HashSet, Hashtable, it becomes extremely important.

Test code:

 Packagecom.rainy.test;ImportJava.util.HashSet;ImportJava.util.Set; Public classApp { Public Static voidMain (string[] args) {Set<A> set =NewHashset<a>(); A A1=NewA (); A A2=NewA (); a1.a= "1"; a2.a= "2";        Set.add (A1);                Set.add (A2);  for(A a:set) {System.out.println (A.A); }    }}classA { PublicString A; @Override Public Booleanequals (Object obj) {A Obja=(A) obj; return  This. A.equals (OBJA.A); } @Override Public inthashcode () {return1; }    }

Code results:

2
1

If two objects have the same hash code, but not equal, can they exist simultaneously in the HashMap?

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.