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

Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)

If you are going this route, and memory efficiency isn't paramount, you can keep both an ArrayList and a HashSet as backing stores. If you go this route, only the remove operations -- remove(int) and remove(Object) etc -- will be O(n).
–
Dilum RanatungaOct 15 '11 at 22:03

Duh :P Ok I was being very thick I can just extend ArrayList and ovveride add() to reject duplicates, I don't even need the backing list. This answer pointed this out to me.
–
JamesOct 15 '11 at 22:05

@Bozho true -- however, add() stipulates raising IllegalArgumentException if some property of the element prevents it from being added to the list. I considered its equivalence to some other element of the list such a property. Debatable, perhaps.
–
pholserOct 15 '11 at 22:07

1

This add() method doesn't conform the method's contract. It should not throw an exception on duplicate, but just return false. Note that there are in total 4 add methods which needs to be implemented.
–
BalusCOct 16 '11 at 0:54