I'm tried to create a linkedlist like below
List<Integer> list = new LinkedList<>();
int i = list.getLast();
But when I use getLast() method from LinkedList class, it reports "cannot find symbol "method getLast()"".
It appears that, since getLast() only exists in LinkedList class, and I declared list as a List, so I cast it into a more general form and lost some function.
But I'm curious how Java find a method name? Since I instantiate it as a LinkedList, can't it find this method in instantiated class? Is there any documents I can read about
The problem is that the List interface does not expose a getLast() method, which is particular to the implementation LinkedList. You have several options here. If you want to declare your List as just that, then you may cast the linked list variable before calling getLast():
List<Integer> list = new LinkedList<>();
list.add(1);
int i = ((LinkedList<Integer>)list).getLast(); // but make sure it's a linked list
Another option would be to just declare your list as a linked list:
LinkedList<Integer> list = new LinkedList<>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With