简体   繁体   English

为什么我的LinkedList不包含addLast()方法?

[英]Why my LinkedList doesn't contains addLast() method?

I have a strange problem I really can't understand. 我有一个奇怪的问题我真的无法理解。

I've created a LinkedList in this way: 我用这种方式创建了一个LinkedList

List<String> customList = new LinkedList<String>();

If check the type of customList using list instanceof LinkedList i get true , so customList is a LinkedList. 如果使用list instanceof LinkedList检查customList的类型我得到true ,那么customList是LinkedList。

Now, if I try to execute the method addLast() on customList i get an Eclipse error: 现在,如果我尝试在customList上执行方法addLast(),我会收到Eclipse错误:

 The method addLast(String) is undefined for the type List<String>

The method addList is defined in the class LinkedList but the only way to use this method is to declare customList as a LinkedList and not as a List, in this way: addList方法在LinkedList类中定义,但使用此方法的唯一方法是将customList声明为LinkedList而不是List,这样:

LinkedList<String> customList= new LinkedList<String>();

or I have to use a cast: 或者我必须使用演员:

((LinkedList<String>) list).addLast(...);

I really don't understand this kind of behaviour, is there someone who can give me some hint? 我真的不明白这种行为,有人能给我一些提示吗? Can you also give me some link or other reference in order to understand this problem? 你能否给我一些链接或其他参考,以了解这个问题?

Thanks in advance 提前致谢

addLast is declared in the LinkedList class, but not in the List interface. addLastLinkedList类中声明,但不在List接口中声明。 Therefore you can only call it using variables of LinkedList type. 因此,您只能使用LinkedList类型的变量来调用它。 However, for a variable of List type you can call add instead, since it adds the element to the end of the List . 但是,对于List类型的变量,您可以调用add ,因为它将元素添加到List的末尾。

When the compiler sees a List variable, it doesn't know the runtime type of the object that would be assigned to that variable. 当编译器看到List变量时,它不知道将分配给该变量的对象的运行时类型。 Therefore it can only let you call methods of the List interface. 因此,它只能让您调用List接口的方法。 For example, you might assign to your variable an ArrayList instance which doesn't have an addLast method, so it can't let you call methods of LinkedList that are not declared in List (or a super-interface of List ). 例如,您可以分配给您的变量的ArrayList不具有一个实例addLast方法,所以它不能让你调用的方法LinkedList未在申报List (或超接口List )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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