问题
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