Joakim Hansson
Joakim Hansson

Reputation: 544

Comparing Objects in java fails

I have just started to work a little with Java and trying to compare two objects with each other by overriding the equals method. I've been debugging this for quite a while trying to understand why it keeps returning false.

I've stripped it down to make it really clear. As you can see in the picture, everything matches in the else if condition.. Why on earth is it returning false?!:

enter image description here

 public boolean equals(Object obj) {

    if(obj == null)
        return false;
    if(getClass() != obj.getClass())
        return false;
    final User user = (User)obj;

    int h1 = CalculateByteArray(this.macAddress);
    int h2 = CalculateByteArray(user.macAddress);

    char[] c1 = this.userName.toCharArray();
    char[] c2 = user.userName.toCharArray();

    if(this.userName == null || this.macAddress == null){
        if(user != null)
            return false;
    } else if(c1 != c2 || h1 != h2)
        return false;
    return true;
}

Upvotes: 1

Views: 104

Answers (4)

LordAnomander
LordAnomander

Reputation: 1123

The problem is the way how you compare the two char arrays. Use !Arrays.equals(c1, c2) instead.

Upvotes: 2

Yaroslav Rudykh
Yaroslav Rudykh

Reputation: 823

c1 and c2 are objects and by else if(c1 != c2 || h1 != h2) you compare references. You should use Arrays.equals(c1,c2)

Upvotes: 4

user987339
user987339

Reputation: 10727

Instead of

if(c1 != c2 || h1 != h2)

use

if(!Arrays.equals(c1,c2) || h1 != h2)

Arrays.equals is used to compare arrays, since in your case c1 and c2 are arrays you should use this.

Upvotes: 3

fge
fge

Reputation: 121830

Arrays are not == to one another.

What you want is to use Arrays.equals(). Or, in your case, !Arrays.equals(), for c1 and c2.

Upvotes: 4

Related Questions