在使用
Java中的泛型时,我有点不方便.请考虑以下代码:
/**
* MyElement class is simply a wrapper for a generic object.
*/
public static class MyElement {
public final T OBJ;
public MyElement(T obj) {
this.OBJ = obj;
}
}
/**
* MyElementList contains an array list of MyElements of the given type, T.
* This represents a class that uses a list of MyElements of a certain type,
* and this list can be accessed in an unmodifiable format.
*/
public static class MyElementList {
//Properties
private List> elementList = new ArrayList();
//CTOR
public MyElementList(List> initElements) {
elementList.addAll(initElements);
}
//Getter
public List> getElements() {
return Collections.unmodifiableList(elementList);
}
}
public static void main(String[] args) {
//New list of elements
//Notice that I did not explicitly specify the type for 'MyElement'
List theElements = new ArrayList(Arrays.asList(
new MyElement[] {
new MyElement("E 1"),
new MyElement("E 2"),
new MyElement("E 3")
}
));
//Also notice I did not explicitly specify the type for 'MyElementList'
MyElementList theList = new MyElementList(theElements);
//The following does not work.
//It seems to not work because theList.getElements() returns a 'List'
//not necessarily a 'List' which is what I would expect it to
//return...
//Why???
for(MyElement e : theList.getElements()) {
System.out.println(e.OBJ.toString());
}
//Currently my work around is to do the following, but I do not like
//having to introduce another variable, and I would rather just do the
//one above
List listOfElements = theList.getElements();
for(MyElement e : listOfElements) {
System.out.println(e.OBJ.toString());
}
//How come the first 'for-each' loop method does not work?
//Is there anyway I could get it to work?
//THANK YOU!
}
在main方法中,如果我没有为’MyElementList’指定类型参数,’getElements()’方法只返回’List’,而不是’List< MyElement>‘.这很不方便,因为如果我想迭代每个’MyElement’,我需要引入另一个变量作为临时列表,如代码所示.
>为什么’getElements()’方法不返回’List< MyElement>‘?
>没有对’MyElementList’进行重大更改我有什么办法可以解决这个问题吗?
>这是一个糟糕的设计实践吗?
我使用的IDE是Netbeans 7.2
提前致谢!
编辑
谢谢大家的快速回复.我对这里的社区印象非常深刻.我得出以下结论:
>如果没有指定泛型提示,Java会忽略一个类的所有其他相关通用提示 – 这有点蹩脚,但我可以忍受它.
>使用泛型时,最佳做法是在创建类的实例时实际指定泛型类型.这似乎是最面向对象的解决方案.
再次感谢!