ratzip
ratzip

Reputation: 1671

Can different objects with same value for the attributes have same hashcode in Java

I am new to Java, I have a question about the hashcode for Java objects:

public class HelloWorld
{
  String name;
  int age;
}

will different objects with same value for the attributes have same hashCode?

HelloWorld hello1 = new HelloWorld();
hello1.name = "hello";
hello1.age = 20;

HelloWorld hello2 = new HelloWorld();
hello2.name = "hello";
hello2.age = 20;

will hello1 and hello2 have same hashCode?

And also, is it possible that objects with different value for the attributes have the same hashCode?

Upvotes: 1

Views: 871

Answers (3)

Pallav Kabra
Pallav Kabra

Reputation: 448

equal objects means equal hashcode.

equal hashcode doesn't mean equal object.

nonequal hashcode means nonequal objects.

Upvotes: 0

assylias
assylias

Reputation: 328568

You have not overriden the hashCode() method, so the hashCode will essentially be random and therefore may or may not be the same for two different objects, regardless of their fields' values. The probability of getting the same hashCode would be very low though.

Upvotes: 1

OrangeDog
OrangeDog

Reputation: 38749

Any class can override hashCode() to return whatever it wants, so yes.

If you need to test for object equality then use equals(), for object identity use ==.

Two equal objects are supposed to return equal hashes, but two unequal objects can also return equal hashes. Most classes that represent data will need to override both methods.

Upvotes: 0

Related Questions