1

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?

ratzip
  • 1,571
  • 7
  • 28
  • 53
  • 3
    Yes, they can. Yes, it's possible. – Nikolas Charalambidis Aug 30 '18 at 10:25
  • how to implement the hashCode to generate distinct result? – ratzip Aug 30 '18 at 10:42
  • Use a [perfect hashing function](https://en.wikipedia.org/wiki/Perfect_hash_function) which is collision free. However, this is NOT a goal of `Object::hashCode` method. It should not assure distinct values for each. Its main purpose is optimization of searching in the hash structures like `HashSet` or `HashMap`. – Nikolas Charalambidis Aug 30 '18 at 10:44
  • 2
    @ratzip You can't - `hashCode` returns an `int`, which is limited to 4 billion values. But you can create a much larger number of different objects : some of them, while not having the same field values, will have the same `hashCode`. – assylias Aug 30 '18 at 10:46

3 Answers3

1

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

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.

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
0

equal objects means equal hashcode.

equal hashcode doesn't mean equal object.

nonequal hashcode means nonequal objects.

Pallav Kabra
  • 418
  • 3
  • 7