I would like to avoid duplicate entries in ArrayList

I am looking for an object, such as an ArrayList, that will allow me to avoid duplicate entries. For example, it might have a method that calls "contains ()" to validate each record before adding it to an ArrayList.

ArrayList<String> al = new ArrayList<String>();
if(!al.contains("red")){
  al.add("red");
}

Is there something similar?

+3
source share
1 answer

ArrayLists and lists are not designed to avoid duplicates at all, they are designed as a type of collection that maintains the order of multiple elements. If you want the collection to be more appropriate for the assignment, you need a set:

Set<String> set = new HashSet<String>();

, , . : , , equals() hashcode(), .

, , LinkedHashSet .

+8

Source: https://habr.com/ru/post/1796022/


All Articles