Set
is an obvious choice, if I do not want to have duplication on my list of data.
However, Set
doesn't have get(int index)
method : Why doesn't java.util.Set have get(int index)?
Several suggestions to implement a pseudo get(int index)
and none of them are efficient.
toArray
and access the new array by index.for
loop to access the indexed element by count.Is there any advanced data structure, which enables me to
get(int index)
. The simplest approach is to have a composite collection which contains a HashSet
and an ArrayList
. Your add
operation would try to add it to the set, and only add it to the list if that has actually added a new item. The get
operation would just get from the list.
Do you ever need to remove values? If not, that makes life simpler - otherwise, removing an item would be an O(N) operation. Not necessarily a problem, but something to bear in mind.
How about BiMap<Integer, T>
A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With