简体   繁体   English

为什么Java编译器在以下代码中为LinkedListDescingIterator给出“错误:找不到符号”?

[英]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这是相关的JavaDocs API
  • Running Java 7.. In case that is issue.运行 Java 7 .. 以防万一。 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我建议使用提供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.

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