[英]How can I iterate over all elements in my generic list List<T> backwards and do the intended operation?
[英]How Do I Iterate Generic List Using For Each Type For Loop
我已经获得了一个创建列表的列表,我可以使用'for each'类型的'for'循环遍历列表,而不是为Iterator构建一个构造函数。 问题是当我下面的代码时,我得到错误消息“只能迭代数组或java.lang.Iterable的实例”。 这是代码:
public static void main(String[] args) {
GList<InnerList> list = new GList<InnerList>();
GList<InnerList> numList = new GList<InnerList>();
InnerList lst = new InnerList ();
Scanner sc = new Scanner(System.in);
String answer;
while (true){
System.out.println ("Do you want to create a list (y/n)? ");
answer = sc.next();
if (answer.equals("y")){
System.out.println("Enter the name of the list: ");
answer = sc.next();
lst.setName(answer);
if (list.isEmpty()== true){
list.insertFirstItem(lst);
}
else {
list.insertNext(lst);
}
}
while (true){
System.out.println("Do you want to enter a number (y/n)?");
answer = sc.next();
if (answer.equals("y")){
System.out.println("Enter Number: ");
answer = sc.next();
try {
int num1 = Integer.parseInt(answer);
lst.setInner(num1);
if (list.isEmpty() == true){
list.insertFirstItem(lst);
}
else {
list.insertNext(lst);
}
}
catch (NumberFormatException e){
System.out.println("You must enter an number! " + e);
sc.close();
}
}
return;
}
}
for (GList<InnerList> ilName : list){ //here are my error msgs. I also tried replacing GList<InnerList> with 'InnerList' and String.
for(GList<InnerList> ilInts : list){
System.out.println(ilName);
System.out.println(ilInts);
}
}
}
有人可以帮我理解为什么集合应该可迭代时,为什么GList不被视为java.lang.iterable的实例吗?
谢谢。
它不被视为java.lang.Iterable
的实例,因为它没有实现接口java.lang.Iterable
。 就如此容易。 将其声明更改为
public class GList<T> implements Iterable<T>
你会很乐意使用它的foreach循环。 但是因为list
是GList<InnerList>
一个实例,并且因为GList<InnerList>
包含InnerList
实例(至少,我猜是这样),所以循环应该是:
for (InnerList innerList : list) {
...
}
这是语法错误,coorect语法是,
for(InnerList ilName : GList) {
for(InnerList ilInts : GList) {
System.out.println(ilName);
System.out.println(ilInts);
}
}
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.