-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?

4
  • use HASHSET, it accept only unique values Commented May 29, 2017 at 8:03
  • @DivyeshPatel, wrong, hashmap contains unique keys. Regarding the question, what type of objects are you storing in the arraylist? Commented May 29, 2017 at 8:03
  • you have to correctly implement equals() and hashCode() of your custom object class for it to be able to check contains Commented May 29, 2017 at 8:04
  • @Denny the object contains name and an id with getters and setters Commented May 29, 2017 at 8:06

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

every set disallows duplicate entries. which exactly he should use depends on further requirements. you should edit your answer and suggest Set as primary option to use
@XtremeBaumer Yes
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.