I have a class with a HashMap<k,v>
.
The type of the values of this HashMap
is a static class which has two different objects as attributes. i.e.,
public class Example {
private HashMap<String, StaticClassExample> map;
private static class StaticClassExample {
private Object1 o1;
private Object2 o2;
//...
}
//...
}
And my question is how can I do this operation efficiently:
public List<Object1> getAllObject1() {}
I know that I can do: map.values()
and then iterate the values collection and get Object1 from each StaticClassExample, but this wouldn't be efficient.
It's possible what I ask or I must create another hashmap for my purpose?
If you don't mind some memory overhead, you could keep a separate list with the o1-values:
Of course, this requires you to encapsule the HashMap inside the class and never give a straight access to it, because then someone using the class could modify the HashMap directly, and the List would no longer be in sync with the Map. Note that
getAllObject1
returns an unmodifiable view of the internal list, so it can't be modified from outside of the class.