CoderTheTyler
CoderTheTyler

Reputation: 869

Two objects with same data are not the same?

I have a test class like so:

public class CompareObjects {

public static class Obj {
    public int i;

    public Obj(int i) {
        this.i = i;
    }
}

public static void main(String[] args) {
    Obj o1 = new Obj(0);
    Obj o2 = new Obj(0);

    if(o1 == o2) {
        System.out.println("Equal");
    }else{
        System.out.println("Not equal");
    }
}

}

I though the test would return "Equal", but it didn't. Why doesn't Java consider two objects with equal components not the same? Am I doing something wrong here? I have a feeling I completely overlooked something when I started learning Java.

Also, I tested the two against each other with the equals() method, and I get the same result. My reason for this question is that I would like to be able to test an ArrayList with the contains() method to see if one object has the same components as another and therefore equal. Any ideas?

Upvotes: 1

Views: 2377

Answers (4)

tckmn
tckmn

Reputation: 59343

== compares the references to the object. For example:

Obj a = new Obj(0);
Obj b = a;
//a == b

Try implementing equals():

public static class Obj {
    public int i;

    public Obj(int i) {
        this.i = i;
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) return true;
        if (!(other instanceof Obj) || other == null) return false;
        return i == ((Obj)other).i;
    }

    @Override
    public int hashCode() {
        return i;
    }
}

Then, you can use if(o1.equals(o2)) {. However, this is not really a good example, read this (link) for more information.

Upvotes: 4

Eng.Fouad
Eng.Fouad

Reputation: 117675

== compares the reference equality, i.e if they refer to the same object in the memory.

You need to override equals() method, and use it whenever you want to compare their values. Also, override hashCode() which is used by HashMap for example.

Upvotes: 1

Alex Coleman
Alex Coleman

Reputation: 7326

The == operator does not check for equality in class data; rather, it checks to see if they are the same location in memory. If you did o2 = o1 instead of initializing them the same way, they would be the same location in memory, so o2==o1 would return true. However, since they were initialized some separately, it returns false. Instead, you should define an equals method and implement that.

Upvotes: 0

moonwave99
moonwave99

Reputation: 22820

== returns true only if you are comparing the same object [i.e. the same memory location].

If you want to compare objects by their fields, you have to overload the equals() method, in order to induce an equivalence relation over them.

public boolean equals(Object other){

    return this.i == other.i;

}

Be sure that the equals() method respects reflexivity, symmmetry, transitivity.

Upvotes: 2

Related Questions