我有一个数组列表的数组列表。我正在尝试遍历它们。但是我一直收到编译错误。我要去哪里错了。有没有更好的方法来迭代。
代码:
import java.util.ArrayList;
public class ListofLists {
public static ArrayList family() {
// ArrayList of ArrayLists
ArrayList<ArrayList<String>> couples = new ArrayList<ArrayList<String>>();
ArrayList<String> husbands = new ArrayList<String>();
husbands.add("brad");
husbands.add("jessie");
couples.add(husbands);
ArrayList<String> wives = new ArrayList<String>();
wives.add("jolie");
wives.add("jena");
couples.add(wives);
return couples;
}
public static void main(String[] args) {
ArrayList couples = family();
for (Object couple : couples) {
for (String person: couple) {
System.out.println(person);
}
}
}
}
编译错误:
required: array or java.lang.Iterable
found: Object
预期产量:
brad
jessie
jolie
jena
您需要的是以下物品:
public static void main(String[] args) {
ArrayList<ArrayList<String>> couples = family();
for (ArrayList<String> couple : couples) {
for (String person : couple) {
System.out.println(person);
}
}
}
基本上,您是将对familiy()的调用结果存储在未知类型的ArrayList中。它会自动装箱到“对象”中,并且for-each不适用于“对象”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句