0

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?

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
Marlen
  • 85
  • 2
  • 8

4 Answers4

3

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;
}
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
0

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

Community
  • 1
  • 1
grunk
  • 14,718
  • 15
  • 67
  • 108
0

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.

antonio
  • 18,044
  • 4
  • 45
  • 61
0
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

Community
  • 1
  • 1