user3991417
user3991417

Reputation:

The right data structure for random acces and no duplicates

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.

Upvotes: 0

Views: 82

Answers (2)

Jean Logeart
Jean Logeart

Reputation: 53819

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().

Upvotes: 1

Gordon Gustafson
Gordon Gustafson

Reputation: 41209

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.

Upvotes: 0

Related Questions