Is there a no-duplicate List implementation out there?

后端 未结 11 694
悲哀的现实
悲哀的现实 2020-11-29 00:53

I know about SortedSet, but in my case I need something that implements List, and not Set. So is there an implementation out there, in the API or e

11条回答
  •  醉酒成梦
    2020-11-29 01:18

    Here is what I did and it works.

    Assuming I have an ArrayList to work with the first thing I did was created a new LinkedHashMap.

    LinkedHashSet hashSet = new LinkedHashSet()
    

    Then I attempt to add my new element to the LinkedHashSet. The add method does not alter the LinkedHasSet and returns false if the new element is a duplicate. So this becomes a condition I can test before adding to the ArrayList.

    if (hashSet.add(E)) arrayList.add(E);
    

    This is a simple and elegant way to prevent duplicates from being added to an array list. If you want you can encapsulate it in and override of the add method in a class that extends the ArrayList. Just remember to deal with addAll by looping through the elements and calling the add method.

提交回复
热议问题