简体   繁体   中英

Override method “equals” doesn't work over 99 id

I found this code to use ArrayList.contains with java object:

@Override
public boolean equals(Object object)
{
    boolean equals = false;

    if (object != null && object instanceof User)
    {
        equals= this.getId() == ((User) object).getId();
    }

    return equals;
}

Until objects with id 99, this method work fine, but over 99 it returns ever false, can someone help me?

if(users.contains(user)){return true;}

Java uses caching of numbers for non-primitive types. So until some value (127 for Integer) you'll have same object for numbers.

Change your '==' to equals() to make it work.

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