Skip to content
Advertisement

Tag: hashcode

Add unique elements in HashSet based on attributes of framework provided non-editable object classes

I am trying to generate a HashSet containing unique Employee instances. Uniqueness should be established based on the object properties. The problem is that I end up with having duplicates. Note that Employee class is provided by a framework, and it’s not possible to provide custom implementations for equals() and hashCode(). Employee class: This would result in a Set mapped

How can UserDefined class be a key of hashmap if hashCode() & equals() return same value

I am trying to implement HashMap with UserDefined class as Key, i am successfull even when I implement both hashCode() (returns 0 for every object) & equals() (returns false for every object). My Code output:- Can anyone let me know the reason how it’s working Answer This is happening because equals is returning false. The equals/hashCode contract is completely broken.

Hashcode value for Map Entry

As per javadocs hashcode for a map.entry is defined as : Plz confirm, if a bitwise XOR operator is used for calculating the hashcode value for a map entry? Answer Yes, it indeed is a bitwise XOR operator. I tried & got the same result for both the hashcode() method & by using ^ operator.

How to create a HashMap with two keys (Key-Pair, Value)?

I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like: For A[2][5], map.get(2,5) which returns a value associated with that key. But how do I create a hashMap with a pair of keys? Or in general, multiple keys:

How could a LinkedHashMap fail to find an entry produced by an iterator?

Under what circumstances given a correct implementation of hashCode and equals() can the following code return false? Answer Most likely scenario I can think of would be even though hashCode is “deterministic”, it may be based on mutable fields. If you change the fields used to compute hashCode after it’s put in the Map, then you won’t be able to

Why doesn’t String’s hashCode() cache 0?

I noticed in the Java 6 source code for String that hashCode only caches values other than 0. The difference in performance is exhibited by the following snippet: Running this in ideone.com gives the following output: So my questions are: Why doesn’t String’s hashCode() cache 0? What is the probability that a Java string hashes to 0? What’s the best

Advertisement