views:

480

answers:

6

I am trying to compare the value of 2 instances of x inside an iterator.

x is a reference type containing its own data members. I am trying to compare one instance of x against another to determine if the values inside each are the same.

if (x.equals(x))

keeps evaluating to true when actually the value of each instance of x is different.

Cheers.

+1  A: 

This is a hard question to answer with the details given. They have to be objects and not primitives to have a .equals method. So has the equals method been overridden in a way that is causing faulty comparisons to be done? That would be the place that I would be looking at.

Matt
A: 

It sounds like you are comparing references and not data.

EDIT: From the API doc for Object: "The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). "

e.g. If 'X' or it's parent classes do not override equals then when you call equals then it will be comparing the references, which if they are the same object will always be the equal.

By the sounds of it you need to override the equals method in the class 'X', but then again, what you say seems to indicate that they are the same reference anyhow?

javamonkey79
yuh, how do I compare the data?
burntsugar
using equals() that is what it is used for
hhafez
No they are different references. Trying to override equals now. Cheers
burntsugar
A: 

The equals method in the Object class performs an instance-equals operation. it is common, however, for subclasses of Object to override this method to perform a relative-equals operation, where the values within the target object are tested against the values of the object in question. In your case, you are most likely using a subclass of Object that has overriden the equals method. It would be good to know how the equals method of your class X is implemented.

akf
+7  A: 

Assuming your code doesn't really look like this

X x = new X();
if(x.equals(x))

but more like

X x = new X();
X y = new X();

if(x.equals(y)) { }

And you are getting wrong values for x.equals(y) then your implementation of equals is broken.

Go to your Class X and check how equals is implemented. If it is not implemented in X check in the super class.

hhafez
A: 

I'm going to assume that your two X objects are actually different objects, and not mistakenly the same object. In this case, the problem is the equals() implementation for that class. Check your class and its superclasses for the equals() implementation, and make sure its actually comparing intelligently. If necessary, write your own.

class Square
{
    public int length;

    public boolean equals( Square s )
    {
        return this.length == s.length;
    }
}
Curtis Tasker
A: 

If you decide to override equals(), also override hashcode()

John Doe