Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declared a List, Implement as LinkedList, cannot use getLast() method

Tags:

casting

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

like image 670
Alex Yu Avatar asked Oct 24 '25 06:10

Alex Yu


1 Answers

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<>();
like image 71
Tim Biegeleisen Avatar answered Oct 28 '25 05:10

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!