Why does Java compiler give "error: cannot find symbol" for LinkedList descendingIterator in the following code?

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

您正在尝试对 List 引用调用 descendingIterator。编译器不知道运行时类型是 LinkedList,因此会出现编译错误。

如果要访问此方法,可以将引用定义为 LinkedList:

LinkedList<Integer> l = new LinkedList<>();

List is an interface and LinkedList is an implementation of 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();
    }
}

跟随校长

“Coding to interfaces, not implementation.”

我建议使用Deque interface that provides descendingIterator()方法

Deque<Integer> deque = new LinkedList<>();
Iterator<Integer> iterator = deque.descendingIterator();

相反。