简体   繁体   中英

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
  • 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,

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.

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<>();

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM