Java LinkedList is all similar to arrays except the elements don’t to store in contiguous locations. All elements are linked to each other using memory reference.
LinkedList is a class that implements the List interface and belongs to java.util.LinkedList package.
Each LinkedList element will have a reference of next LinkedList element.
LinkedList can acts as both list and queue as it implements List and Queue interface.
Each LinkedList block will have two sections:
As shown above, yellow highlighted block represents the memory location of each respective block highlighted as red. Every block contains data and memory reference of next block.
The previous blocks will always contain the memory reference of next block.
The last block will contain data and memory reference as null. Last block wouldn’t have any further block.
LinkedList<String> linkedList = new LinkedList<String>();
The above expression will create a LinkedList of type “String”. All the String and null value can be added in this LinkedList.
Similarly, we can create a list to store data of type int.
LinkedList<Integer> linkedList = new LinkedList<Integer>();
LinkedList uses add() method to add elements in the list.
list.add("first");
Add element in list at specific location or index using add() method:
list.add(1, "first");
This will add element at first index or position using addFirst() method:
list.addFirst(1, "first");
Add element at last index or position using addLast() method:
list.addLast(3, "first");
Update element in list at specific location or index using set() method:
list.set(1, "first");
We can use remove() method to remove element from the list.
list.remove("first");
remove element in list from specific location or index using remove() method:
list.remove(1);
This will remove element from first index or position using removeFirst() method:
list.removeFirst(1);
Remove element from last index or position using removeLast() method:
list.removeLast(1, "first");
OUTPUT:
Collections class provides sort() method to sort LinkedList elements alphabetically.
size(): The size() method will return the number of elements present in the list.
clear(): The clear() method will make list empty and remove all the elements from list.
contains(): The contains() method check either the particular element is exist or not in the list.
isEmpty(): returns true if we don’t have any element in the list.
getFirst() & getLast(): Methods will return first and last element from the LinkedList.
Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.
📝 Blogs
javadoubts.com © All rights reserved