简体   繁体   中英

Why isn't my equals method working?

I'm using an ArrayList , and at one point in the program I'm using the contains method to check if a certain item is contained in the ArrayList . The ArrayList holds objects of type CharProfile , a custom class, and it's seeing if a char is contained within it.

So it's using the equals method in the contains method, I assume. So something like CharProfile.contains(char) , but it's not working.

I overrode the equals method in CharProfile:

@Override
public boolean equals(Object o) {
    if (this.character == (Character)o) {
        return true;
    }
    else {
        return false;
    }
}

So it should be using my equals method when CharProfile is trying to use it, right? So why won't it work?

(In terms of "not working" I'm referring to the fact that contains always returns false.)

You are comparing a reference type using ==, which is wrong. You must use equals , with proper null -checks added.

But this is just the beginning. Your main problem is that you are trying to compare a CharProfile object to a Character object. You probably need this instead:

public boolean equals(Object o) {
  return o instanceof CharProfile 
     && this.character.equals((CharProfile)o).character;
}

This assumes that your character field is never null. If it can be null, you need to check that before dereferencing it, as well.

你重写equals,以便测试引用的相等性,运算符的默认行为==

You need to use equals (). You can also make it a oneliner and be more explicit in your cast.

@Override
public boolean equals(Object o) {
    return o instanceof Character && this.character.equals(Character.class.cast(o));
}

You have to use the equals() method and DO NOT forget to override the hashCode() method as well. They go hand in hand.

Some people don't know this, but if using eclipse you can right click choose Source-> and Generate hashCode() and equals()...

But, I suggest that you learn what they're for first before using this convenience.

For example, You have CharProfile as below.

List<CharProfile> list = new ArrayList<CharProfile>();
list.add(new CharProfile('a'));
list.add(new CharProfile('b'));
list.add(new CharProfile('c'));

When list.contains('a') is does, the JVM will not call Override equals() method of CharProfile .

For more clear;

public class Data {
    public boolean equals(Object o) {
        System.out.println("I am data");
        return false;
    }
}

When list.contains(new Data()) is does, the JVM will not call Override equals() method of Data . Now, You will get message like I am data. .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM