My usecase is like in which I need to maintain a collection of unique items. I may need to frequently add or remove items from the collection at an index(which I have as member of the item currently, but I am open to modification), and while doing that I need to update index of items.
I am not able to decide which Java collection would suit my needs best. HashSet and SortedSet both guarantee uniqueness, but not sure how index part can be taken care of.
Advertisement
Answer
According to the question + comments, you have the following fundamental requirements for the collection:
- The elements in the collection must be unique.
- The collection must maintain the elements in an order specified by the user.
- The collection elements must have unique indexes representing the element’s current position.
- The indexes must adjust as elements are inserted and deleted.
There is no (single) Java SE collection type that does 1 and 2, 3 or 4.
The only Java SE collection type that supports and can maintain an arbitrary ordering is List
, so you need to start with that. Something like this for instance:
public class MyList<E> extends ArrayList<E> { ... @Override public void add(int pos, <E> e) { if (this.contains(e)) { throw new SomeException("already in collection"); } this.add(pos, e); } }
Note that HashMap<Integer, E>
is a possible alternative, but adjusting the indexes as elements are added and removed is complicated. (Comparing the performance characteristics is not straightforward, but the chances are that it won’t matter in your use-case.)