Dave's Brain

Browse - Programming Tips - How can I avoid duplicates in an ArrayList ?

Date: 2016jul7
Language: Java

Q.  How can I avoid duplicates in an ArrayList ?

A.  If the ArrayList is fairly short:

void addUnique(ArrayList<String> list, String item) { if (!list.contains(item)) { list.add(item); } }
If you always do this when appending you won't get any duplicates. If you are given an ArrayList which might have unwanted duplicates I would convert it into a HashSet then back into an ArrayList.
list = new ArrayList<String>(new HashSet<String>(list));

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.