java list 转 treeset,为什么Java不能转换ArrayList< TreeSet< Integer>>到列表< Set< Object>&g...

I'm attempting to do something that seems rather simple: sum the sizes of a list of sets. Netbeans gives the following warning/error:

actual argument java.util.ArrayList> cannot be converted to java.util.List> by method invocation conversion

for the following two pieces of code:

/**

* Sums the sizes of all sets in a list. Note that while there will be

* no duplicate elements in a single set, "sister" sets may contain

* elements, so the value returned is **not** equal to the number of unique

* elements in all sets.

* @param list, a List of Sets

* @return the number of elements contained in all sets

*/

public static int sizeOfListOfSets(List> list) {

int size = 0;

for (Set set : list) {

size += set.size();

}

return size;

}

and then calling it with the following:

ArrayList> testList = new ArrayList>();

TreeSet testSet;

int size = 0;

testSet = new TreeSet();

testSet.add(new Integer(++size));

testSet.add(new Integer(++size));

testList.add(testSet);

testSet = new TreeSet();

testSet.add(new Integer(++size));

testList.add(testSet);

int expResult = size;

int result = Helpers.sizeOfListOfSets(testList);

the last line gives the compilation error:

error: method sizeOfListOfSets in class Helpers cannot be applied to given types;

1 error

So, why can't java.lang.Integer be converted to java.lang.Object?

解决方案

A List is not a List. If Java allowed that, then you could call the method with List and you will be broken. As Jeremy Heiler pointed out you can use List extends Object> and you will be fine. This means every type which extends Object is allowed. ? is called a wildcard in generic jargon.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值