-1

I have an empty arraylist of objects that has global scope. I need to add items to the arraylist from a different activity and also not to add items that are already present in it( no duplicates ).

I have an issue when the item is added to the list from an activity in which the item is received from an intent, the item gets added even if the list contains the item already. However the item is added only once on the activity starts.
But on finnishing the activity and starting it again adds the item again creating duplicates.

I simply use the arraylist.contains(object) to check if the object is present in the list. Is there any way I can not get the duplicates or remove them?

Pushpendra
  • 2,791
  • 4
  • 26
  • 49
Ice Bunny
  • 67
  • 1
  • 9

2 Answers2

2

You can try with HashSet .

HashSet is implementation of Set Interface which does not allow duplicate value .

HashSet hashSetOBJ = new HashSet();
hashSetOBJ.add("ONE");
hashSetOBJ.add("ONE");
hashSetOBJ.add("TWO");


    Iterator itOBJ = hashSet.iterator();
    System.out.println("Value in HashSet :");
    while(itOBJ.hasNext())
    System.out.println(itOBJ.next()); // Op will ONE and TWO
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

You need to override the equals method your custom class.

e.g.

public boolean equals(Object c) {
    if(c !instanceof CustomClass) {
        return false;
    }
    // TODO change to your type and change the methods
    CustomClass that = (CustomClass)c;
    return this.id.equals(that.getId()) && this.id.equals(that.getId());
}

Then you can call list.contains(obj) to see if the list already contains an equal object. Change CustomClass to your required type and you can add more checks if it is required.

A better solution is to use Sets. Look here for more info.

Denny
  • 1,766
  • 3
  • 17
  • 37