Reputation: 544
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?!:
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
Reputation: 1123
The problem is the way how you compare the two char
arrays. Use !Arrays.equals(c1, c2)
instead.
Upvotes: 2
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
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
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