1

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;
}
1
  • you are just comparing chars by reference.... use equals as fge suggested Commented Apr 8, 2016 at 11:29

4 Answers 4

4

Arrays are not == to one another.

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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.

1 Comment

I can't believe I missed that.. The thing is, before I added the arrays I simply tried comparing the strings which failed too.. As a C# user I am not used to doing it this way haha. Thanks a lot!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.