LinkedList class 中没有 peek() 方法?

No peek() method in LinkedList class?

LinkedList<String> queue = new LinkedList<String>(); // queue.peek()
Queue<String> queue2 = new LinkedList<String>();// queue2.peek()
List<String> queue3 = new LinkedList<String>(); // queue3.peek() error!

我用三种不同的方式声明了链接列表class。我知道linkedlistclass是queue和list接口的实现,但是用第三种方式声明,想在eclipse中使用peek()方法时,为什么会报错?他们都一样 class ?

您正在将 LinkedList 声明为列表对象。 List 接口不提供 peek() 方法。 这就是为什么你不能使用它。 看这里ref

java.util.List 没有 peek 方法。当您使用 LinkedList<String> 创建列表时,java 在内部将其转换为 List<String>,因此您的 peek 方法将丢失。

您创建的三个对象不同,因为它们被转换为不同的类型。

是的,LinkedList 中有一个 peek 方法 class。

peek() method 在 LinkedList class 中可用。由于您使用的是 List 类型的引用,而 List 接口没有方法 peek(),编译器不允许您调用它。

在前两个示例中,您使用的是 LinkedList and Queue 类型的引用,因此您可以调用 peek() 方法。

参见为什么要声明一个接口然后实例化一个对象 在 Java?

您不能从 的实例调用特定于 具体 class 的方法抽象接口到它。

LinkedList class 和 List 接口之间的关系就像 Cat class 和 Animal 接口之间的关系:

Animal 的实例可以调用 .breathe().reproduce() 等方法,并以不同方式响应对这些方法的调用,而方法本身保持不变(这就是接口的存在) ), 但接口不应该有 .sharpenClaws() 方法,因为不是所有的动物都有爪子。

此时如果要调用.sharpenClaws()方法,需要先询问"but, which animal is this?"


所以,就像您对 Cat.sharpenClaws() 方法(伪代码)所做的那样...

if (animal is Cat) {
  //remove ambiguity by defining that the (animal) is a (Cat)
  Cat thisCat = (Cat)animal;
  //make the cat sharpen it's claws
  thisCat.sharpenClaws();
}

...要使用LinkedList.peek()方法,您需要将其转换回更具体的class:

if (aList instanceof LinkedList) {
  ((LinkedList)aList).peek();
}