简体   繁体   中英

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?

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.

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.

equal objects means equal hashcode.

equal hashcode doesn't mean equal object.

nonequal hashcode means nonequal objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM