Differentiate between Java Objects

时间:2015-05-04 19:22:52

标签: java

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?

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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

答案 2 :(得分: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