[英]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
跟着校長
“編碼接口,而不是實現。”
我建議使用提供descendingIterator()方法的Deque接口
Deque<Integer> deque = new LinkedList<>();
Iterator<Integer> iterator = deque.descendingIterator();
反而。
您正在嘗試對List
引用調用descendingIterator
。 編譯器不知道運行時類型是LinkedList
,因此編譯錯誤。
如果要訪問此方法,可以將引用定義為LinkedList
:
LinkedList<Integer> l = new LinkedList<>();
List 是一個接口,LinkedList 是 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.