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.