Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between removeFirst() remove(0) on the LinkedList?

I am trying to return and remove first element from the LinkedList. Below are the two options I can see.

First Approach:

LinkedList<String> servers = new LinkedList<String>();
....
String firstServerName = servers.removeFirst();

Second Approach

List<String> servers = new LinkedList<String>();
....
String firstServerName = servers.remove(0);
  • Is there any preference which one we should use?
  • And what is the difference between the above two? Are they technically same thing in terms of performance? What is the complexity involve here?

What is the most efficient way to return and remove first element from the linked list in Java? I need to do this operation more frequently on my LinkedList.

like image 393
john Avatar asked Oct 30 '25 21:10

john


1 Answers

removeFirst(): Remove the first element in the list. -> O(1)

remove(index): Removes the element at the given position from the list. -> O(n)

So, in your case, because you only want to remove the first element, you can choose to removeFirst().

like image 91
Hector Montero Avatar answered Nov 02 '25 11:11

Hector Montero