1

I have a below Java Class.

public class MyClass {

private final String id;

public MyClass(final String id) {
    this.id= id;
}

public String getId() {
    return id;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((id == null) ? 0 : id.hashCode());
    return result;
}

@Override
public boolean equals(final Object obj) {
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    final MyClass other = (MyClass) obj;
    if (id== null) {
        if (other.getId != null)
            return false;
    } else if (!id.equals(other.getId))
        return false;
    return true;
}

}

Now I am creating 2 objects of this class.

MyClass obj1 = new Object("ABCD");
MyClass obj2 = new Object("ABCD");

As per my class definition these 2 objects are equal. But in heap I believe 2 different objects would be created.

If I want to prove although both the objects are equal but still they are different how can I do it?

GD_Java
  • 1,359
  • 6
  • 24
  • 42

3 Answers3

4
if(obj1 == obj2)
   ; // Same object

if(obj1.equals(obj2))
   ; // Equal objects (as defined by your equals() method).

A distinct object is created when new is used, so yes there are two equal but separate objects.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • `A distinct object is created when new is used, so yes there are two equal but separate objects` : except for classes that have pooling mechanism (`String`, `Ingeter` between -256 and 255...). But yeah, I admit that this is not rally the point of the question :D – Dici May 04 '15 at 19:36
  • 1
    @Dici: integer pool is from -128 to 127. – Jeroen Vannevel May 04 '15 at 19:37
  • @Dici `new String()` will create a new object, same with Integer. Pooling can only happen if String is created as a literal, or `Integer/Long` is autoboxed or created with `Integer.valueOf()/Long.valueOf()`. – Kayaman May 04 '15 at 19:39
  • @JeroenVannevel right – Dici May 04 '15 at 19:47
  • @Kayaman hmm that's true, just tested. I thought it also worked with `new`, my bad – Dici May 04 '15 at 19:49
0

Not sure what exactly you want to do, but this should answer you :

  • equals implements the logical equality
  • == is the physical equality (identity), which means that if it returns true, it is the actual same object
Dici
  • 25,226
  • 7
  • 41
  • 82
0

For comparing objects equality you need to use equals().

If you want to check if references show directly to the same object you have to use == operator.

Code snippet:

MyClass obj1 = new Object("ABCD"); // create first object at heap
MyClass obj2 = new Object("ABCD"); // create second object at heap

obj1.equals(obj2); // true
obj1 == obj2;      // false
obj1 == obj1       // true
catch23
  • 17,519
  • 42
  • 144
  • 217