1

我有一堂课HashMap<k,v>。this 的值的类型HashMap是一个静态类,它有两个不同的对象作为属性。IE,

   public class Example {
      private HashMap<String, StaticClassExample> map;
      private static class StaticClassExample {
           private Object1 o1;
           private Object2 o2;
           //...   
      }
      //...
   }

我的问题是如何有效地执行此操作:

   public List<Object1> getAllObject1() {}

我知道我可以做到:map.values()然后迭代值集合并从每个 StaticClassExample 中获取 Object1,但这不会有效。我可能会问什么,或者我必须为我的目的创建另一个哈希图?

4

1 回答 1

0

如果您不介意一些内存开销,您可以使用 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返回内部列表的不可修改视图,因此无法从类外部对其进行修改。

于 2012-01-28T10:06:41.623 回答