遍历 LinkedList 但出现错误 "for-each not applicable to expression type",怎么了?
Iterating through LinkedList but getting error "for-each not applicable to expression type", what is wrong?
我目前正在实现一个特里树,这是我目前的代码:
1 public class DictionaryDLB{
2
3 private Node root = new Node();
4
5 private class Node {
6 private Character val;
7 private LinkedList<Node> next = new LinkedList<Node>();
8 }
9
10 public void put(String key)
11 { root = put(root, key, 0); }
12
13 private Node put(Node x, String key, int d){
14 if (x == null) x = new Node();
15 if (d == key.length()) { x.val = '$'; return x; }
16 char c = key.charAt(d);
17 for(Node item : x.next){
18 if(c == item.val){
19 item = put(item, key, d+1);
20 }
21 }
22 return x;
23 }
24 }
但是,当我尝试编译时,我在私有 put()
方法中遇到此错误:
DictionaryDLB.java:17: error: for-each not applicable to expression type
for(Node item : (x.next)){
^
required: array or java.lang.Iterable
found: LinkedList<Node>
1 error
我在网上查找了各种示例,这似乎应该可行,因为 java.util.LinkedList
确实实现了 java.lang.Iterable
。但是,它没有,我很难过。任何帮助或建议将不胜感激。谢谢!
我正在导入 java.util.LinkedList
和 import java.util.*;
,这显然在这种情况下不起作用。必须直接使用 import java.util.LinkedList;
导入它
我目前正在实现一个特里树,这是我目前的代码:
1 public class DictionaryDLB{
2
3 private Node root = new Node();
4
5 private class Node {
6 private Character val;
7 private LinkedList<Node> next = new LinkedList<Node>();
8 }
9
10 public void put(String key)
11 { root = put(root, key, 0); }
12
13 private Node put(Node x, String key, int d){
14 if (x == null) x = new Node();
15 if (d == key.length()) { x.val = '$'; return x; }
16 char c = key.charAt(d);
17 for(Node item : x.next){
18 if(c == item.val){
19 item = put(item, key, d+1);
20 }
21 }
22 return x;
23 }
24 }
但是,当我尝试编译时,我在私有 put()
方法中遇到此错误:
DictionaryDLB.java:17: error: for-each not applicable to expression type
for(Node item : (x.next)){
^
required: array or java.lang.Iterable
found: LinkedList<Node>
1 error
我在网上查找了各种示例,这似乎应该可行,因为 java.util.LinkedList
确实实现了 java.lang.Iterable
。但是,它没有,我很难过。任何帮助或建议将不胜感激。谢谢!
我正在导入 java.util.LinkedList
和 import java.util.*;
,这显然在这种情况下不起作用。必须直接使用 import java.util.LinkedList;