For a project I am working on, I need to keep track of up to several thousand objects. The collection I choose needs to support insertion, selection, and deletion of random elements. My algorithm performs each of these operations several times, so I would like a collection that can do all these in constant time.

Is there such a collection? If not, what are some trade-offs with existing collections? I am using Scala 2.9.1.

EDIT: By "random", I mean mathematically/probabilistically random, i.e., I would like to select elements randomly from the collection using Random or some other appropriate generator.

Please tell us once you've found the collection that does all the mentioned things in constant time.
–
ziggystarNov 28 '11 at 9:44

1

Can you clarify the operations you need -- for example what is an insertion of a random element? Isn't it sufficient if you either add elements at random indices or pull pull elements from random indices, instead of asking for both? Because then you can choose a data structure that support efficient append or prepend along with efficient random access and removal, or vice versa. Do you need an immutable or a mutable data structure?
–
0__Nov 28 '11 at 13:19

2 Answers
2

Define "random". If you mean indexed, then there's no such collection. You can have insertion/deletion in constant time if you give up the "random element" requirement -- ie, you have have non-constant lookup of the element which will be deleted or which will be the point of insertion. Or you can have constant lookup without constant insertion/deletion.

The collection that best approaches that requirement is the Vector, which provides O(log n) for these operations.

On the other hand, if you have the element which you'll be looking up or removing, then just pick a HashMap. It's not precisely constant time, but it is a fair approximation. Just make sure you have a good hash function.