Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

java - what is the difference between == operator and equals()? (with hashcode() ???)

I was learning hashcode in more depth and figured that:

1. If you override equals(), you must override hashcode() too.

2. To find if 2 objects are same object, use == operator

Given those 2 factors, in Java I was assuming that when == operator is used to compare if 2 instances are same or not,

if(object1 == object2)

is actually doing

if(object1.hashcode() == object2.hashcode())

But it appears I was wrong by running the test below.

public class Main {

    public static void main(String[] args){
        Obj1 one = new Obj1();
        Obj1 two = new Obj1();
        //is this calling hashCode() in backend???
        if(one == two) {
            System.out.println("same");
        }
        else {
            System.out.println("nope");
        }
        //this is of course return true
        if(one == one) {
            System.out.println("one and one is same");
        }
    }
}

class Obj1 {
    @Override
    public int hashCode() {
        System.out.println("hashCode() is called");
        return 111;
    }
    @Override
    public boolean equals(Object another) {
        System.out.println("equals() is called");
        return false;
    }
}

According to the test which uses == operator and see if equals() is called and it wasn't.

So my question is if == operator can used to compare if the object is same or not, what is the point of overriding equals() and hashCode() method for comparison? Isn't == operator do the job already?

reference:

Overriding hashCode() - is this good enough?

http://mindprod.com/jgloss/hashcode.html

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

== is identity.

.equals() is equality.

.equals() defaults to just using == (just like hashCode() defaults to System.identityHashCode() but you can override them if there's a more meaningful way to check for equality. Typically this is a sort of "structural" equality. ie: are all of the pieces of this .equal() to all of the pieces of that?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...