[英]Why does Java compiler give "error: cannot find symbol" for LinkedList descendingIterator in the following code?
Why does this code:为什么这段代码:
import java.util.*;
class Playground {
public static void main(String[ ] args) {
List<Integer> l = new LinkedList<>();
Iterator<Integer> i = l.descendingIterator();
}
}
Generate this compiler error生成此编译器错误
./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
Following the principal跟着校长
“Coding to interfaces, not implementation.” “编码接口,而不是实现。”
I suggest to use the Deque interface that provides descendingIterator() method我建议使用提供descendingIterator()方法的Deque接口
Deque<Integer> deque = new LinkedList<>();
Iterator<Integer> iterator = deque.descendingIterator();
instead.反而。
You are trying to call descendingIterator
on a List
reference.您正在尝试对List
引用调用descendingIterator
。 The compiler doesn't know that the runtime type is a LinkedList
, hence the compilation error.编译器不知道运行时类型是LinkedList
,因此编译错误。
If you want to access this method, you could define the reference as a LinkedList
:如果要访问此方法,可以将引用定义为LinkedList
:
LinkedList<Integer> l = new LinkedList<>();
List is an interface and LinkedList is an implementation of List List 是一个接口,LinkedList 是 List 的一个实现
You have the option of explicit typecasting like the following您可以选择显式类型转换,如下所示
Iterator<Integer> i = ((LinkedList<Integer>)l).descendingIterator();
or change your code to be the following:或将您的代码更改为以下内容:
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.