4

please apologize me if it is already existing question in stack overflow, but I would go through so many threads of stack overflow. But still I am unable to understand what they are try to discuss about two references comparison of the same class, please help to come out of this problem. This is my actual analysis

public class A {
  public static void main(String[] args) {
    A object1 = new A();
    A object2 = new A();
    if (object1 == object2)
       System.out.println("Different objects of the same class are equals");
    else
       System.out.println("Different objects of the same class are not equals");
     }
   }

Output : Different objects of the same class are not equals

Now what I am unable to understanding thing is on which bases JVM will check these two objects (object1 and object2). And I would override .equal(), hashCode(), toString() methods in A class. Please see here my total code.

public class A {

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

@Override
public String toString() {
    return "12345";
}

public static void main(String[] args) {
    A object1 = new A();
    A object2 = new A();
    if (object1 == object2)
       System.out.println("Different objects of the same class are equals");
    else
       System.out.println("Different objects of the same class are not equals");
   }
 }

Please give me clear cut explanation, I am very very thankful to them.

vikky
  • 43
  • 8
  • [How do I compare Strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) applies here too. – Sotirios Delimanolis Feb 15 '14 at 17:25
  • It isn't really clear what you're asking. But suffice to say, the answer is probably "`==` is **reference** equality for objects in Java". – Oliver Charlesworth Feb 15 '14 at 17:29
  • Thanks for instant response.Give me one minute I will check and with in two minutes I will get back you please. – vikky Feb 15 '14 at 17:29
  • @OliCharlesworth : Yes, I really want compare two references of same class – vikky Feb 15 '14 at 17:32
  • But I am not getting on which bases jvm will check this condition if (object1 == object2) – vikky Feb 15 '14 at 17:32
  • @OliCharlesworth : like addresses of the references or hashcode of the those references or something else – vikky Feb 15 '14 at 17:34
  • Behind the scenes an object reference could be a pointer (address) but we don't know that and it doesn't have to be. – Radiodef Feb 15 '14 at 17:36
  • The easiest way to represent reference equality in your head is to imagine that the JVM compares the memory addresses contained in the two references. This is not necessarily what's done by the JVM, but that should suffice to make the difference with equals(). `object1` points to the object stored at memory address 54345, `object2` points to the object at memory address 76545. These addresses are not equal, so the objects are not the same. – JB Nizet Feb 15 '14 at 17:42
  • @JBNizet : Hi, Please just correct me if my understanding is wrong, As per your discussion for every object would be store at specific memory location(address) so every reference having it's own address so by that time '==' condition will be false. Am I right ? – vikky Feb 15 '14 at 18:46
  • @JBNizet : Please also guide me how to get the address of the reference in java we have any predefined method is java api ? – vikky Feb 15 '14 at 19:02
  • For what reason would you want the address? – steffen Feb 15 '14 at 19:40
  • http://chat.stackoverflow.com/rooms/51446/discussion-between-aet-and-noslouch – vikky Apr 25 '14 at 17:22
  • From your cell phone 000117 >> ATT bridge number & Pin. Click here: https://att.uc.att.com/att/meet/?ExEventID=8431194 ATT connect link is also accessible on internet. – vikky Apr 25 '14 at 17:22

7 Answers7

1

Two different objects are always different if you compare them using ==, whatever the implementation of equals() (and hashCode(), and toString()) is.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • But if my class is Singleton class then `==` condition will be true then what about this scenario ? – vikky Feb 15 '14 at 18:50
  • Yes, the == condition would be true for that scenario. – kabb Feb 15 '14 at 19:22
  • @kabb : Means memory will location will be override with new reference of previous reference. Am I right ? – vikky Feb 16 '14 at 08:04
  • 1
    If your class is a singleton, you'll only have one signle instance of your class, stored at a given location in memory. All the variables referencing this singleton will point to the same, unique memory location where the singleton object is stored. An object is always == to itself. You seem to confuse reference variables (pointers) and objects. A reference variable is a pointer to an object living somewhere in memory. When you use `==` on two variables, you test if they both reference the same object. – JB Nizet Feb 16 '14 at 08:12
  • Can you please guide me how to get the reference memory location on heap area.Thanks so much. – vikky Feb 20 '14 at 11:17
  • You can't. As simple as that. Why would you want it anyway? – JB Nizet Feb 20 '14 at 11:30
  • Just for knowledge sake more than it nothing is there. – vikky Feb 20 '14 at 11:50
0
== check the reference of the Object.If you create two object of same class then reference will be different.There  will be `NO` difference whether you implement equal or hashcode function
Kick
  • 4,823
  • 3
  • 22
  • 29
0

When you compare two objects in java using ==, it's checking to see if the two objects are in the same location in memory. So when you create two instances of the A class, in your example, they may be the same, but they are both stored in different locations in memory. That's why it says they aren't equal when using ==.

If you want to compare two objects in java, you want to use the equals() method. So instead of using

if (object1 == object2)

you would use

if (object1.equals(object2))

Furthermore, to make this work, you would have to override the equals() method for the class A.

kabb
  • 2,474
  • 2
  • 17
  • 24
0

Class is a template to create many objects.

== is a facility to compare objects: same object or not.

.equals() is a facility to check if objects have the same state.

UPD

I mean in formal theory objects have 1) identity 2) state 3) behavior. So == is for checking the identity and equals() is for checking the state. It's not strictly so in Java but that might help to progress in understanding.

Vitaly
  • 2,760
  • 2
  • 19
  • 26
  • equals() doesn't automatically check if objects have the same state. And objects can be equal even if they don't have the same state. The equals() method is precisely there to decide when two objects are equal. – JB Nizet Feb 15 '14 at 17:31
  • @JB Nizet Right. But eventually this is as I wrote, consider javadoc: `boolean equals(Object obj) Indicates whether some other object is "equal to" this one.` – Vitaly Feb 15 '14 at 17:36
  • 1
    Precisely. The javadoc doesn't say that equal objects have the same state. I know you probably know what equals does and how it works, but your wording is confusing. – JB Nizet Feb 15 '14 at 17:39
  • @JB Nizet Yes, perhaps, it might be confusing.. This is just to let the author of the question an insight about the difference. I mean in formal theory objects have 1) identity 2) state 3) behavior. So `==` is for checking the identity and `equals()` is for checking the state. We know that it's not strictly so in Java but that might help to progress in understanding. – Vitaly Feb 15 '14 at 17:51
  • You should make this last comment your answer. Much clearer IMO. – JB Nizet Feb 15 '14 at 17:54
0

This is the Object.equals() method implementation

/**
 * (...)
 * <p>
 * The {@code equals} method for class {@code Object} implements
 * the most discriminating possible equivalence relation on objects;
 * that is, for any non-null reference values {@code x} and
 * {@code y}, this method returns {@code true} if and only
 * if {@code x} and {@code y} refer to the same object
 * ({@code x == y} has the value {@code true}).
 * <p>
 * Note that it is generally necessary to override the {@code hashCode}
 * method whenever this method is overridden, so as to maintain the
 * general contract for the {@code hashCode} method, which states
 * that equal objects must have equal hash codes.
 *
 * @param   obj   the reference object with which to compare.
 * @return  {@code true} if this object is the same as the obj
 *          argument; {@code false} otherwise.
 * @see     #hashCode()
 * @see     java.util.HashMap
 */
public boolean equals(Object obj) {
    return (this == obj);
}

can't be clearer than that

so if you don't override equals(), you're using this method.

Leo
  • 6,480
  • 4
  • 37
  • 52
0

In your scenario JVM will compare objects on the basis of reference i.e according to the address of two abject. "==" will check whether two object have the same address or not which is clearly not the same as you are using "new" to create object which returns reference of newly created objects.

unknown
  • 241
  • 4
  • 16
0

The == operator checks object identity (two variables refer to the same instance in memory), while equals() defines object equality (two variables represent the same object).

Example:

If a == b and you change a then you also change b.

If a != b but a.equals(b) then a and b are different instances but they are considered equal. Example: If a is in a Set, then this set can not contain b at the same time, because they are equal and sets don't contain duplicates.

The result of toString() is completely irrelevant for object identity or equality.

hashcode() must return the same value for equal instances, but can also return the same hashcode for different (unequal) instances: !a.equals(b) && a.hashcode() == b.hashcode() may be the case. So if you override equals() you have to override the default implementation of hashcode as well.

Your example shows 2x the keyword new. This means you have two instances in memory, so they are definitely not ==, but may equal() each other.

steffen
  • 16,138
  • 4
  • 42
  • 81