What java data structure is an ordered collection, provides the functionality constant time contains method of HashSet, and provides constant time lookup by index much like the get method of ArrayList? Does the Java API contain such a thing? I considered using TreeSet, but according to the Java Docs those operations are O(log n).
2 Answers
The Java standard library does not offer such a class, but you could implement your own without too much trouble. It would be more or less the dual of LinkedHashSet: a List (maybe wrapping ArrayList) that maintains an internal HashSet for constant-time contains() processing.
The Collections API has classes intended to make it easy to implement
collection classes; in this case I would look at implementing a concrete subclass of AbstractList.
Update:
On the other hand, if your idea is that the instances automatically maintain their elements in order, and/or that they disallow duplicate elements, then what you're talking about is not a List at all. In that case you would want to consider implementing a concrete subclass of AbstractSet that adds indexed retrieval methods. You could still wrap a HashSet and an ArrayList, but you would need to expend some effort to keep the list ordered on element insertion.
Comments
Use LinkedHashSet. It is Hash table and linked list implementation of the Set interface, with predictable iteration order.
You will see up to O(n) complexity for insertion or checking the existence of an item in the hash set. However most times you don't see collisions and so in most cases it will be O(1).
4 Comments
LinkedHashSet offers constant-time retrieval, it is only by key, not index.
LinekdHashSetperhaps?