4

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.

  1. toArray and access the new array by index.
  2. Get the iterator, and use a for loop to access the indexed element by count.

Is there any advanced data structure, which enables me to

  1. Avoid duplication.
  2. Have O(1) performance for get(int index).
Community
  • 1
  • 1
Cheok Yan Cheng
  • 49,649
  • 117
  • 410
  • 768

2 Answers2

9

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.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • We need to consider thread safe issues as well right? What I really mean is, during adding item into Set and ArrayList, and adding operation should be atomic. – Cheok Yan Cheng Jun 18 '14 at 05:56
  • 5
    @CheokYanCheng: Well that depends - you didn't mention anything in your requirements about it being thread-safe. Note that most collections in Java *aren't* thread-safe. – Jon Skeet Jun 18 '14 at 05:57
  • We are going to remove element by Object. Is there any special handling needed for removing operation? I though List and Set both provide remove(Object o) method? - I know List's remove(Object o) might not be O(n) – Cheok Yan Cheng Jun 18 '14 at 06:08
  • @CheokYanCheng: They do, but it'll be an O(n) operation. It's trivial to code, but not efficient. Is that an issue? – Jon Skeet Jun 18 '14 at 06:09
3

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.

jmj
  • 225,392
  • 41
  • 383
  • 426
  • 2
    Like my suggestion, this is difficult in terms of removal - because you'd want to update all the indexes. – Jon Skeet Jun 18 '14 at 05:58
  • yes BiMap would can be wrapped to provide proper `remove()` with things taken care inside (finding key and removing it) – jmj Jun 18 '14 at 06:01