0
When we use double equal operator "==" for comparing two objects it will compare their addresses or hascodes generated by JVM?
4 ответов
+ 4
Hello Sparsh Kathpal
You are right. == for objects compares their address.
You can use == only for primitive datatypes (int, double, char...)
For objects you have to use equals.
For example:
String s1 = "hello";
String s2 = "world";
s1.equals(s2) returns false.
0
Hello Denise Roßberg
As you are saying it will check the addresses of the objects but i have also one one doubt that in java there is no way to check what is the address of that object so how == check address. May be it is checking the hashcodes if hashcodes are equal than it will return true otherwise false. But i am not sure which is right it will check addresses or hascodes?
0
As far as I know == compares only the address. The JVM does this:
https://stackoverflow.com/questions/1382026/how-is-the-operator-implemented-in-java#:~:text=The%20%3D%3D%20operator%20just%20compares,just%20a%20standard%20object%20pointer.&text=When%20you%20compare%20two%20object,are%20a%20location%20in%20memory.
The hash code is connected with equals(). Means two objects which are equal should have the same hash code. That's important when you override equals() and hashCode().
But I think you need hash codes for hashsets and hashmaps.