代码之家  ›  专栏  ›  技术社区  ›  Carl

通用工厂和映射值

  •  1
  • Carl  · 技术社区  · 17 年前

    我有一节课要上 Map K Set<V> s、 为了几个不同的目的 V s我想使用通用工厂ala:

    protected static <T> Set<T> SetFactory(int size) {
            return new HashSet<T>(size);
    }
    

    做某事

    for (K key : keySet) map.put(key, SetFactory());
    

    Set<Object> 和 设置<V> Set<V> x = SetFactory();

    除了通过考试,还有其他选择吗 Class<V> 论据 SetFactory() ?

    5 回复  |  直到 17 年前
        1
  •  2
  •   erickson    17 年前

    我真的不明白你的问题。这就是你要找的吗?

    class MyClass {
    
      protected static <T> Set<T> SetFactory(int size)
      {
        return new HashSet<T>(size);
      }
    
      protected static <K, V> Map<K, Set<V>> mapFactory(Collection<K> keys)
      {
        Map<K, Set<V>> result = new HashMap<K, Set<V>>(keys.size());
        for (K key : keys)
          result.put(key, MyClass.<V>SetFactory(20));
        return result;
      }
    
    }
    

    请注意显式类型参数( <V> )关于泛型方法调用。


    更新:

    我可能是错的,但在这里 -不得不把我的班级。在前面似乎很接近必须 铸造你能解释一下区别吗?

    (Set<V>) SetFactory(20) SetFactory 函数具有 V

    在方法调用中使用类型参数很像 new HashSet<V>()

    总是

        2
  •  0
  •   ChssPly76    17 年前

    你需要一个明确的任务:

    for (K key : keySet) {
      Set<V> mySet = setFactory(20);
      map.put(key, mySet);
    }
    

    没有它,编译器就无法知道 <V>

        3
  •  0
  •   skaffman    17 年前

    Apache Commons Collections LazyMap 您在其中提供 Factory 对象,该对象创建贴图的值。您可以提供一个创建设置值的工厂。

    here .

    我希望我正确地解释了你的问题——它相当令人困惑。

        4
  •  0
  •   Yishai    17 年前

    如果你一定要把它放在一行上,你可以把胡说八道的作业放在一行上:

     Set<V> s = null;
     for (K key : keySet) map.put(key, s = setFactory());
    

    但这个答案更多的是展示另一种方法,而不是实际上表明这是一种更好的方法。

        5
  •  0
  •   Carl    17 年前

    protected static <K,V> Map<K,Set<V>> mapFactory(Collection<K> keys) {
        Set<V> holder;
        Map<K,Set<V>> result = new HashMap<K,Set<V>>(keys.size());
        for (K key : keys) result.put(key, holder = SetFactory());
        return result;
    }
    

    甚至让我摆脱了最初分配地图的烦恼。如果我真的想重写这个类,我想我需要在参数列表中添加一个工厂。

    推荐文章