只是想知道这样做是否正确。我想构造我的参数化类的实例,其中一个实例变量是泛型类型。下面的代码有效,但我在主要方法中收到很多警告“SomeObject 是原始类型。对泛型类型 SomeObject 的引用应该被参数化”。
public class SomeObject<T> {
private String description;
private T value;
public SomeObject(String description, T value) {
this.description = description;
this.value = value;
}
public static void main(String args[]){
List <SomeObject> objectList = new ArrayList<SomeObject>();
objectList.add(new SomeObject("Object 1: ", true));
objectList.add(new SomeObject("Object 2: ", 888.00));
objectList.add(new SomeObject("Object 3: ", "another object"));
objectList.add(new SomeObject("Object 4: ", '4'));
for (SomeObject object : objectList){
System.out.println(object.getDescription() + object.getValue());
}
}
最佳答案
The code below works but I get a lot of warnings in the main method "Object is a raw type. References to generic type Object should be parameterized".
警告是因为您在构造 SomeObject
时没有指定类型参数。即。
应该是:
List<SomeObject<?>> objectList = new ArrayList<>();
objectList.add(new SomeObject<Boolean>("Object 1: ", true));
objectList.add(new SomeObject<Double>("Object 2: ", 888.00));
objectList.add(new SomeObject<String>("Object 3: ", "another object"));
objectList.add(new SomeObject<Character>("Object 4: ", '4'));
关于java - 实例化参数化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43614933/