2016-11-08 67 views
1

下面的代码片段不能编译;我有一个泛型类,映射从泛型键K到浮点。我的大多数方法都是以一种真正通用的方式处理这张地图。通用类中的特定类型的约束方法

此外,我想允许用升序整数值初始化映射。显然,这要求我只将方法限制为K = Integer。不幸的是,我得到以下错误:

The method put(K, Float) in the type Map is not applicable for the arguments (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++; 
     } 
    } 
} 
+1

有没有'return'在'SparsePDT'方法o.o – ItamarG3

+4

你知道,'Integer'声明'final'? –

+0

@ItamarGreen谢谢,这只是一个人造物,然后再将其降低为一个玩具的例子。该方法实际上是一个构造函数。 – Chris

回答

4

你可以扩展你的类和基础类指定参数类型:

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的”可保持完全通用的,也用它的地图整数类型。
欲了解更多有关的扩展通用类,您可以阅读here
希望它有帮助。

+0

在C++中,我将我的方法赋予“template :: value,int> :: type = 0>” - 在Java中的替代? – Chris

+1

在Java中,泛型在C++中功能较弱。这是因为它们被包含在这种语言中的时间相当晚,而且Java是向后兼容的。如果你想让你的课程“MyClass”完全通用,这个解决方案(以及类似的)是我想到的唯一的解决方案。 –

1

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

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; 
    } 
}