foreach 不适用于 java.lang.object 并在尝试遍历 java 中的数组列表的数组列表时出现编译错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21358740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
foreach not applicable to java.lang.object and compilation error when trying to iterate through array list of array lists in java
提问by Shankar
I have an array list of array lists. And I am trying to iterate through them. However I keep getting compilation error. Where am I going wrong. Is there a better way to iterate.
我有一个数组列表的数组列表。我正在尝试遍历它们。但是我不断收到编译错误。我哪里错了。有没有更好的迭代方法。
Code:
代码:
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);
}
}
}
}
Compilation Error:
编译错误:
required: array or java.lang.Iterable
found: Object
Expected Output:
预期输出:
brad
jessie
jolie
jena
采纳答案by Reinstate Monica
WHat you need is the following:
您需要的是以下内容:
public static void main(String[] args) {
ArrayList<ArrayList<String>> couples = family();
for (ArrayList<String> couple : couples) {
for (String person : couple) {
System.out.println(person);
}
}
}
Basically, you were storing the results from your call to familiy() in an ArrayList of unknown type. It was automatically getting boxed to Object, and for-each doesn't work for Objects.
基本上,您将调用 familiy() 的结果存储在未知类型的 ArrayList 中。它会自动装箱到 Object,而 for-each 不适用于 Objects。
回答by mojiayi
iterator is a feature of collection,class Object itself does not provide such feature. Look at my code.It's work well.
迭代器是集合的一个特性,类 Object 本身并没有提供这样的特性。看看我的代码,它运行良好。
package com.test;
import java.util.ArrayList;
import java.util.List;
public class ListOfLists {
public static List<List<String>> family() {
// ArrayList of ArrayLists
List<List<String>> couples = new ArrayList<List<String>>();
List<String> husbands = new ArrayList<String>();
husbands.add("brad");
husbands.add("jessie");
couples.add(husbands);
List<String> wives = new ArrayList<String>();
wives.add("jolie");
wives.add("jena");
couples.add(wives);
return couples;
}
public static void main(String[] args) {
List<List<String>> couples = family();
for (List<String> couple : couples) {
for (String person : couple) {
System.out.println(person);
}
}
}
}
}