I\'m working with a large ArrayList
, and I would repeatedly need to select a random key from a random HashMap (and do some stuff with it).
After spending some time, I came to the conclusion that you need to create a model which can be backed by a List
and a List
to maintain your keys. You need to keep the access of your List
and List
, just provide the operations/methods to the caller. In this way, you will have the full control over implementation, and the actual objects will be safer from external changes.
Btw, your questions lead me to,
values()
method also returns Set
.This example, IndexedSet, may give you an idea about how-to.
[edited]
This class, SetUniqueList, might help you if you decide to create your own model. It explicitly states that it wraps the list
, not copies. So, I think, we can do something like,
List list = new ArrayList(map.keySet());
SetUniqueList unikList = new SetUniqueList(list, map.keySet);
// Now unikList should reflect all the changes to the map keys
...
// Then you can do
unikList.get(i);
Note: I didn't try this myself. Will do that later (rushing to home).