简体   繁体   中英

Checking if ArrayList<> cointains a object dont work

My app downloading a Events from sqldatabase and add it to ArrayList<>. It do aduplicate so I wrote:

public static ArrayList<Events> list = new ArrayList<Events>();

  static void addevhlp(Events e){

        if (list.contains(e)){
         Log.d("","it cointains")
        }
        else {
            list.add(e);
        }

    }

But it never say me the list cointans element. What I'm doing wrong?

you have to override equals in Events , and define when two events are equals. The default implementation checks for equal object's reference. For instance, if your Events class has an int id field

@Override
public boolean equals(Object o) {
    if (!(o instanceof Events)) {
         return false;
    }
    Events event = (Events) o;
    return id == event.id;
}

You should overrides equals and hashCode in your Events object.
See : Best implementation for hashCode method for detail about hashCode

According to the documentation about ArrayList.contains :

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

So, contains uses the equals implementation of your Events class to check if it holds the object.

if (list.contains(e))

If the events e has the same Reference than the one you have in the ArrayList the contains will work. but If you want to check if the value is the same, but with a different Reference, you have to check if the properties of your events are exists or equals.

or you can simply use LINQ with List instead of ArrayList C# how to determine, whether ArrayList contains object with certain attribute

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