As per the definition addLast(), the addLast() method is used to add element to the last of the list. But here in the following code that's not happening.
LinkedList<Integer> demo = new LinkedList<>();
demo.addLast(15);
demo.addFirst(1);
demo.add(10);
System.out.println(demo);
The output is
[1, 15, 10]
But as per the definition the output should have been
[1, 10, 15]
Because the addLast() method should be adding 15 to the last of the list. I'm not sure what exactly is the issue here.
Code snippet : Code snippet
addLast
adds an item at the end of the list - it doesn't mean it will remain at the end of list when additional items are added.
Let's track the code:
addLast(15)
will add 15 at the end of this list, so it's now [15]addFirst(1)
will add 1 at the beginning of the list, so it's now [1, 15]add(10)
will add 10 at the end of the list, so it's now [1, 15, 10]