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

余生长醉 提交于 2020-01-06 08:05:21

问题


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
  • Here is the relevant JavaDocs API
  • Running Java 7.. In case that is issue. Thought it had been around for donkeys years.
  • Here is a canned example elsewhere.
  • You could copy/paste code from here into this website to see,

回答1:


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



回答2:


You are trying to call descendingIterator on a List reference. The compiler doesn't know that the runtime type is a LinkedList, hence the compilation error.

If you want to access this method, you could define the reference as a LinkedList:

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



回答3:


Following the principal

“Coding to interfaces, not implementation.”

I suggest to use the Deque interface that provides descendingIterator() method

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

instead.



来源:https://stackoverflow.com/questions/59591101/why-does-java-compiler-give-error-cannot-find-symbol-for-linkedlist-descendin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!