【问题标题】:Constraining method in generic class to specific type将泛型类中的方法限制为特定类型
【发布时间】:2016-11-08 10:19:22
【问题描述】:

下面的代码sn-p不能编译;我有一个带有 Map 的通用类,它从通用键 K 映射到 Floats。我的大多数方法都以真正通用的方式处理此地图。

此外,我想允许使用升序整数值初始化地图。显然,这需要我将方法限制为仅 K=Integer。不幸的是,我收到以下错误:

类型Map中的put(K, Float)方法不适用于参数(K extends Integer, Float)

非常感谢这里的任何帮助!

public class MyClass<K> {
    Map<K,Float> myMap;

    <K extends Integer> MyClass(int size){
       distribution = new HashMap<K,Float>();
       Integer bar = 0;
       while(bar<size){
          Float rnd = ThreadLocalRandom.current().nextFloat();
          myMap.put(bar,rnd);
          bar++;
       }
    }
}

【问题讨论】:

  • SparsePDT 方法中没有 return o.o
  • 你知道,Integer 被声明为 final 吗?
  • @ItamarGreen 谢谢,在将其简化为玩具示例之前,这只是一个人工制品。该方法实际上是一个构造函数。
  • @F.Lumnitz 我知道。或者,我也可以使用可以迭代的非最终类型。

标签: java generics dictionary


【解决方案1】:

您可以扩展您的类并为基类指定参数类型:

class MyClass<K> {
    Map<K,Float> myMap;
}
class Derived extends MyClass<Integer>{
    void SparsePDT(int size){
        myMap = new HashMap<Integer,Float>();
        Integer bar = 0;
        while(bar<size){
            Float rnd = ThreadLocalRandom.current().nextFloat();
            myMap.put(bar,rnd);
            bar++;
        }
    }
}

它使“MyClass”类可以保持完全通用,也可以将它的映射与 Integer 类型一起使用。
有关扩展泛型类的更多信息,您可以阅读here
希望对您有所帮助。

【讨论】:

  • 在 c++ 中,我将我的方法归因于 "template::value, int>::type = 0 >" - 扩展类是 Java 中唯一的选择吗?
  • 在 Java 中,泛型的功能不如 C++ 强大。这是因为它们很晚才被包含在这种语言中,并且 java 是向后兼容的。如果你想让你的类“MyClass”完全通用,这个解决方案(和类似的)是我唯一想到的。
【解决方案2】:

作为子类的另一种方式是使用静态创建方法:

class MyClass<K> {
    private final Map<K, Float> myMap;

    public MyClass() {
        myMap = new HashMap<>();
    }

    public static MyClass<Integer> create(int size) {
        MyClass<Integer> result = new MyClass<>();
        for(int i = 0; i < size; i++) {
            Float rnd = ThreadLocalRandom.current().nextFloat();
            result.myMap.put(bar,rnd);
        }
        return result;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多