[英]Why does Java compiler give "error: cannot find symbol" for LinkedList descendingIterator in the following code?
为什么这段代码:
import java.util.*;
class Playground {
public static void main(String[ ] args) {
List<Integer> l = new LinkedList<>();
Iterator<Integer> i = l.descendingIterator();
}
}
生成此编译器错误
./Playground/Playground.java:5: error: cannot find symbol
Iterator<Integer> i = l.descendingIterator();
^
symbol: method descendingIterator()
location: variable l of type List<Integer>
1 error
跟着校长
“编码接口,而不是实现。”
我建议使用提供descendingIterator()方法的Deque接口
Deque<Integer> deque = new LinkedList<>();
Iterator<Integer> iterator = deque.descendingIterator();
反而。
您正在尝试对List
引用调用descendingIterator
。 编译器不知道运行时类型是LinkedList
,因此编译错误。
如果要访问此方法,可以将引用定义为LinkedList
:
LinkedList<Integer> l = new LinkedList<>();
List 是一个接口,LinkedList 是 List 的一个实现
您可以选择显式类型转换,如下所示
Iterator<Integer> i = ((LinkedList<Integer>)l).descendingIterator();
或将您的代码更改为以下内容:
import java.util.*;
class Playground {
public static void main(String[ ] args) {
LinkedList<Integer> l = new LinkedList<>();
Iterator<Integer> i = l.descendingIterator();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.