java list 不指定类型_java – 如果不指定泛型类型,方法不会返回元素列表,而只返回列表...

在使用

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会忽略一个类的所有其他相关通用提示 – 这有点蹩脚,但我可以忍受它.

>使用泛型时,最佳做法是在创建类的实例时实际指定泛型类型.这似乎是最面向对象的解决方案.

再次感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值