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;
}
Joakim Hansson
  • 544
  • 3
  • 15

4 Answers4

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.

fge
  • 119,121
  • 33
  • 254
  • 329
4

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

Yaroslav Rudykh
  • 803
  • 6
  • 12
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.

user987339
  • 10,519
  • 8
  • 40
  • 45
  • 1
    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! – Joakim Hansson Apr 08 '16 at 11:33
2

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

LordAnomander
  • 1,103
  • 6
  • 16