如果您不介意一些内存开销,您可以使用 o1 值保留一个单独的列表:
public class HashMapList
{
private HashMap<String, StaticClassExample> map = new HashMap<String, HashMapList.StaticClassExample>();
private List<Object> o1List = new LinkedList<Object>();
public static class StaticClassExample
{
private Object o1;
private Object o2;
}
public void addStaticClassExample(String key, StaticClassExample example)
{
StaticClassExample oldVal = map.put(key, example);
if(oldVal != null)
{
o1List.remove(oldVal.o1);
}
o1List.add(example.o1);
}
public StaticClassExample getStaticClassExampleByKey(String key)
{
return map.get(key);
}
public void removeStaticClassExampleByKey(String key)
{
StaticClassExample removed = map.remove(key);
if(removed != null)
{
o1List.remove(removed.o1);
}
}
public List<Object> getAllObject1()
{
return Collections.unmodifiableList(o1List);
}
}
当然,这要求您将 HashMap 封装在类中,并且永远不要直接访问它,因为使用该类的人可以直接修改 HashMap,List 将不再与 Map 同步。请注意,它getAllObject1
返回内部列表的不可修改视图,因此无法从类外部对其进行修改。