I need to store unique objects in some datastructure, but also I need access by index like in ArrayList or plain array. Maybe there is some elegant way to do this without using convertions from set to array, iteration through all elemnts, checking value while adding to ArrayList and others. I would be grateful for any help and advices.
-
3Can you explain about why you need access by index, and what the index represents? You can do sequential iteration through a hash set, so you don't need the random access/indexing for that. – Nir Friedman Sep 21 '14 at 16:07
2 Answers
You should have a look at ListOrderedSet
from Apache Commons Collections:
Decorates another Set to ensure that the order of addition is retained and used by the iterator.
If an object is added to the set for a second time, it will remain in the original position in the iteration. The order can be observed from the set via the iterator or toArray methods.
The ListOrderedSet also has various useful direct methods. These include many from List, such as get(int), remove(int) and indexOf(int). An unmodifiable List view of the set can be obtained via asList().

- 1
- 1

- 52,687
- 11
- 83
- 118
Make your own class containing a HashSet<T>
and an ArrayList<T>
. For the add
/append
operation, if the element is not already in the set, append it to the list and add it to the HashSet. You'll use about twice as much memory as a normal ArrayList, but you'll get O(1)
random access and contains operations.

- 40,133
- 25
- 115
- 157
-
Why twice as much? It should just be two pointers to the same object no, in which case it will depend on the object size but will never be as bad as double and could could be almost the same if the object is large. – Nir Friedman Sep 21 '14 at 16:12
-
1@NirFriedman `ArrayList` is backed by an array that is at worst [`1.5n` elements](http://stackoverflow.com/questions/4859873/when-an-arraylist-resizes-itself-how-many-elements-does-it-add). I haven't delved too deep into the implementation of `HashSet`, but I believe there will be at least `1.333n` buckets (with the default load factor of `0.75`). This combo data structure will use `O(n)` memory regardless, but it's reasonable to estimate it as *about* twice the memory of an `ArrayList`. You're probably correct in saying the size of the objects will dominate the size of the pointers though. – Gordon Gustafson Sep 21 '14 at 16:29