我编写了代表集合的类。在集合中,我有一个 ArrayList 的字段“元素”。类中的所有方法都是泛型。
我写的第一个方法是获取另一个 Set 作为参数并返回新的 Set,该新 Set 保持 this.Set 与参数之间的联合。这是方法:
public Set<E> union(Set<E> s){
Set<E> toReturn = new Set<>();
for(E toAdd : this.elements) {
toReturn.addToSet(toAdd);
}
for(E toAdd : s.elements)
toReturn.addToSet(toAdd);
return toReturn;
}
现在我想写另一个方法,它作为参数 ArrayList> 并返回新的 Set,它表示 this.Set 与参数 ArrayList 内的所有 Set 之间的联合。但我无法访问 ArrayList 中的集合。这是我的代码:
public Set<E> union(ArrayList<Set<E>> s) {
Set<E> toReturn = new Set<>();
for(E el : s) {
toReturn.addToSet(s.union(el));
}
return toReturn;
}
编译器告诉我“方法 union(E) 未定义类型 ArrayList>。
我很乐意提供一些帮助。谢谢
最佳答案
您在 for 循环中使用了错误的变量,s 是 ArrayList,而 toReturn 是您要使用 addAll(otherSet); 方法计算并集的集合。如果是的话,你可能正在使用 Guava 的 Set 库,你可以继续使用 union(otherSet) 方法。
你在哪里:
for(E el : s) {
toReturn.addToSet(s.union(el));
}
更好的说法是:
for(Set<E> el : s) {
toReturn.addToSet(toReturn.union(el));
}
关于java - 无法访问 ArrayList 的 ArrayList(通用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56102358/