Java Guava CartesianProduct

老子叫甜甜 提交于 2019-12-13 06:24:47

问题


I am exploring Java Guava Library by writing small snippets of code. Here is what I wrote for finding the cartesian product of n-sets. Documentation here

//allLists populated above
...
List<Set> interimList = new ArrayList<Set>();
for(List<String> tmp : allLists) //converting List<List> to List<Set> 
{
    Set interimSet   = new HashSet(tmp);
    interimList.add(interimSet);
}
System.out.println(interimList);
Sets.cartesianProduct(interimList);

But this is not compiling. The last line Sets.cartesianProduct is not accepting List<Set>. But according to documentation isn't that its signature?

public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets)

ERROR MESSAGE: Cannot Resolve method cartesianProduct(java.util.List<java.util.Set)


回答1:


The problem is you have created a raw Set, instead of a generic one.

What happens is you're trying to pass a List<Set<Object extends String>> to the Sets.cartesianProduct() and this is why you're receiving a compile-type error.

This compiles:

List<Set<String>> interimList = new ArrayList<Set<String>>();
//converting List<List<String>> to List<Set<String>>
for (List<String> tmp : allLists) { 
    Set<String> interimSet   = new HashSet<String>(tmp);
    interimList.add(interimSet);
}
System.out.println(interimList);
Sets.cartesianProduct(interimList);


来源:https://stackoverflow.com/questions/20449279/java-guava-cartesianproduct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!