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);
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.
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().
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