Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java combination of Set and List interfaces

I have a data structure, for which I am currently using an ArrayList. I realised that in this structure I do not want any duplicates to be present. My first thought was to use some form of set, however the order is also important. After a bit of googling and searching the Collections docs I found LinkedHashSet which almost does the job. Unfortunately, one of the primary reasons for preserving order is because I am using the get(int index) method of the ArrayList for random access, and I can't see any way around this.

More concisely - I need a set that preserves order and allows random access. None of the classes I have so far looked at provide this functionality. Does anyone know of a class that offers this, or will I have to make it myself? If it is the latter case are there any pitfalls when creating such a structure that people are aware of?

(Alternatively, a quick and easy way of checking for and removing duplicates form an ArrayList or similar structure would suffice)

EDIT: for clarity, it is the order that elements are added to the list that is important, not how they compare to one another

like image 701
James Avatar asked Dec 27 '22 12:12

James


1 Answers

SetUniqueList from commons-collections:

List<Foo> uniqueList = SetUniqueList.decorate(new ArrayList<Foo>());

(unfortunately, commons-collections still doesn't support generics, so you'll have to suppress a warning here)

like image 147
Bozho Avatar answered Jan 03 '23 09:01

Bozho