Check if an item exists in a HashSet using a hash

Is it possible to check if an object is in a HashSet if I have only the hash code of the object and not the object itself?

+5
source share
6 answers

You cannot, because hashCode is only used to search for the bunker in which the object is stored in a HashSet . There can be several items in the same box, and the HashSet uses equals to determine if the item found exists in the bin to which hashCode was bound.

A bunker can contain several elements with the same hashCode , so knowing only hashCode not enough.

+9
source

You can create a special object, something like this

 int hashCode = 1; // your new Object() { @Override public boolean equals(Object obj) { return true; } @Override public int hashCode() { return hashCode; } }; 
+3
source

No, you can’t. Finding an object in a hashed collection requires both equals and hashcode. The hashcode method indicates in which bucket the object can be found, and the equals method finds the object in the bucket.

An example of a real world would be a house with many people in it. If you tell me to go find someone in a house, I will ask you two questions:

  • What house am I going to?
  • Who will I find?

Here (1) they will respond to hashcode, and (2) they will answer using the equal method.

+1
source

A hashCode not a unique identifying property, so no.

+1
source

No, because 2 objects can have the same hash code. The uniqueness of objects in Set (or keys in Map ) is checked on hashCode() and equals() .

+1
source

All objects have a hashCode () method called by HashSet, HashMap, ecc ..

You can override this method to define your own logic.

  @Override public int hashCode() { return <<MY CODE HERE>>; } 

or, more simply, iterate over your HashSet and check the hashCode () value

 int myHash = 123; for(Object o:mySet){ if(myHash == o.hashCode()){ // do something.. } } 
0
source

Source: https://habr.com/ru/post/1214013/


All Articles