Why is the default hash () in java bad?

if I remember correctly the default implementation of hashCode () in the java of an object of type Object (), this will return the memory address of the object. When we create our own classes, I read that we want to override hashCode () so that when inserted into the assembly associated with the hash, for example HashMap (), it will work correctly. But why a bad memory address?

I’m sure that we will have a lot of memory flaws and you will have collisions, but the only time I see that this is a problem is where you are dealing with TONS data and have very little memory, and then it will start affect performance because hash collections are in java resolution conflicts by chaining (the bucket will refer to a list of values ​​that were resolved to the same hashcode / index).

+5
source share
4 answers

The default implementation works fine if each object is unique. But if you override equals (), you implicitly say that objects with different addresses can be equivalent to each other. In this case, you must also override hashCode ().

Think of the String class.

String s1 = new String("foo");
String s2 = new String("foo");

, - . .

s1 == s2         // false, different addresses
s1.equals(s2)    // true, same contents

- . String hashCode(), , -. hashCode(), :

a.equals(b) , a.hashCode() == b.hashCode().

: equals(), hashCode().

+20

, hashmap, . , equals. equals, , - , -.

+1

equals, , hashCode, hashCode , . , .

hashCode

0

, hashCode() , API hashmap.

API , , .

hashCode() , , , - .

, , . , .

To get values ​​from the data structure in the entire program, you will need to save links to all keys that you previously inserted (using a different data structure). You cannot use keys that are β€œsimilar” in terms of the state of the object.

Person steve1 = new Person("Steve","21","engineer");
Person steve2 = new Person("Steve","21","engineer");

map.put(steve1,"great worker");

map.get(steve2); 
// returns null because "steve2" is not considered a key like "steve1"

map.get(steve1); 
// returns "great worker"
0
source

All Articles