LinkedList:
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure.
The important points about Java LinkedList are:
- Can contain duplicate elements.
- Maintains insertion order.
- Is non synchronized.
- Manipulation is fast because no shifting needs to be occurred.
Doubly Linked List:
A doubly linked list whose nodes contain three fields: a value, the link to the next node, and the link to the previous node.In case of doubly linked list, we can add or remove elements from both side.
Following is the list of the constructors provided by the LinkedList class.
LinkedList( ) - Default constructor:
This constructor builds an empty LinkedList.
Consider following example where we create an empty LinkedList with it's default constructor.
LinkedList(Collection c):
This constructor builds an linked list that is initialized with the elements of the collection c.
Consider you have a Set collection and you want to covert from Set to an LinkedList. This constructor comes handy for these operations, like, converting any other collection to LinkedList or creating a replica of existing LinkedList.
Example for converting as Set to a LinkedList:
LinkedList(int capacity):
This constructor builds a linked list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an linked list.
Suppose you already have an Array with the size 5 and you decided to convert Array to LinkedList. You can create Linkedlist with exactly the size of the Array which you want to convert.
Note: Arrays.asList() converts any array to List which is from Arrays class. We will discuss more about Arrays class later in this tutorial.
Now you know how to create a LinkedList. LinkedList class has so many predefinaed methods which helps to finish out task super easy. We will discuss some important methods.
Note: For Java best practices in creating a Linked List please follow post Programming to Interfaces.
Add Method:
There are 2 add methods available in LinkedList.
They are,
boolean add(Object o): appends an element to the end of an LinkedList.
void add(int index, Object element): Inserts the specified element at the specified position index in this list. When you insert an element at any index, then it shifts the following elements to make room. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).
Example below shows how to use effectively above add methods:
set Method:
Replaces the element at the specified position with the specified element. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
A doubly linked list whose nodes contain three fields: a value, the link to the next node, and the link to the previous node.In case of doubly linked list, we can add or remove elements from both side.
Following is the list of the constructors provided by the LinkedList class.
LinkedList( ) - Default constructor:
This constructor builds an empty LinkedList.
Consider following example where we create an empty LinkedList with it's default constructor.
import java.util.LinkedList; public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<Integer> elements = new LinkedList<>(); System.out.println(elements.size()); } }
Output:
0
LinkedList(Collection c):
This constructor builds an linked list that is initialized with the elements of the collection c.
Consider you have a Set collection and you want to covert from Set to an LinkedList. This constructor comes handy for these operations, like, converting any other collection to LinkedList or creating a replica of existing LinkedList.
Example for converting as Set to a LinkedList:
import java.util.LinkedList; import java.util.HashSet; import java.util.Set; public class LinkedListDemo { public static void main(final String[] args) { final Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); //Converting Set to linkedlist final LinkedList<Integer> linkedList = new LinkedList<>(set); System.out.println(linkedList); //Creating replica of existing LinkedList final LinkedList<Integer> linkedList2 = new LinkedList<>(linkedList); System.out.println(linkedList2); } } Output: [1, 2, 3] [1, 2, 3]
LinkedList(int capacity):
This constructor builds a linked list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an linked list.
Suppose you already have an Array with the size 5 and you decided to convert Array to LinkedList. You can create Linkedlist with exactly the size of the Array which you want to convert.
import java.util.LinkedList; import java.util.Arrays; public class LinkedListDemo { public static void main(final String[] args) { final Integer[] intArray = {1, 2, 3, 4, 5}; //Converting Array to LinkedList final LinkedList<Integer> linkedList = new LinkedList<>(5); System.out.println(linkedList.size); } } Output: 5
Note: Arrays.asList() converts any array to List which is from Arrays class. We will discuss more about Arrays class later in this tutorial.
Now you know how to create a LinkedList. LinkedList class has so many predefinaed methods which helps to finish out task super easy. We will discuss some important methods.
Note: For Java best practices in creating a Linked List please follow post Programming to Interfaces.
Add Method:
There are 2 add methods available in LinkedList.
They are,
boolean add(Object o): appends an element to the end of an LinkedList.
void add(int index, Object element): Inserts the specified element at the specified position index in this list. When you insert an element at any index, then it shifts the following elements to make room. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()).
Example below shows how to use effectively above add methods:
import java.util.LinkedList; public class LinkedListDemo { public static void main(final String[] args) { // Create an LinkedList and add two strings.
final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); System.out.println(list); // Add an extra element at index 0. // This will move all the existing following elements to make room. list.add(0, "Benz"); System.out.println(list); } } Output: [Audi, BMW] [Benz, Audi, BMW]
addAll Method:
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException, if the specified collection is null.
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException, if the specified collection is null.
import java.util.LinkedList;public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>();
list.add("Audi"); list.add("BMW"); list.add("Benz"); System.out.println("Original LinkedList: " + list); // Let's create a duplicate LinkedList of above using addAll method final LinkedList<String> duplicate = new LinkedList<>(); duplicate.addAll(list); System.out.println("Duplicate LinkedList: " + duplicate); } } Ouput: Original LinkedList: [Audi, BMW, Benz] Duplicate LinkedList: [Audi, BMW, Benz]
import java.util.LinkedList;public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); System.out.println("LinkedList before Set operation: " + list);
//Replace 0th element which is Audi with Honda list.set(0, "Honda"); System.out.println("LinkedList After Set operation: " + list); } } Ouput: LinkedList before Set operation: [Audi, BMW, Benz] LinkedList After Set operation: [Honda, BMW, Benz]
Get Method:
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index >= size()).
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(final String[] args) {
final LinkedList<String> list = new LinkedList<>();
list.add("Audi");
list.add("BMW");
list.add("Benz");
// Get 2nd element which is BMW. We have to use index 1 as list index starts from 0.
System.out.println("2nd Element of the LinkedList: " + list.get(1));
}
}
Output:
BMW
size Method:
Returns the number of elements in this list.
import java.util.LinkedList;public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); // print the current size of the LinkedList System.out.println("The size of the LinkedList: " + list.size()); } }
Output:
The size of the LinkedList: 3
contains Method:
Searches whther a given element is present in the existing list.
import java.util.LinkedList; public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); System.out.println("Is list contains Audi: " + list.contains("Audi")); } } Output: The size of the LinkedList: 3 Is list contains Audi: true
clear Method:
Removes all of the elements from this list. i.e. resets the list and size to 0.
isEmpty Method:
Check whether a list is empty means no elements in it. Returns true if empty or else false.
Let's use both clear and isEmpty methods in below example:
import java.util.LinkedList; public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); // print the current size of the LinkedList System.out.println("The size of the LinkedList: " + list.size()); // Reset the list using clear method list.clear(); System.out.println("Is LinkedList empty: " + list.isEmpty()); } } Output: The size of the LinkedList: 3 Is LinkedList empty: true
Removes the element at the specified position in this list. Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index >= size()).
import java.util.LinkedList;public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); // print the current size of the LinkedList System.out.println("LinkedList before removing BMW which is 2nd element: " + list); // Removing BMW which is 2nd element. We have to use index 1 to for 2nd element as list index // starts from 0; list.remove(1); System.out.println("LinkedList after removing BMW which is 2nd element: " + list); } } Output: LinkedList before removing BMW which is 2nd element: [Audi, BMW, Benz] LinkedList after removing BMW which is 2nd element: [Audi, Benz]
indexOf Method:
Returns the index in of the first occurrence of the specified element, or -1 if the List does not contain this element.
import java.util.LinkedList;public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); // print the current size of the LinkedList System.out.println("Printing index of BWM: " + list.indexOf("BMW")); } } Output: Printing index of BWM: 1
toArray Method:
Returns an array containing all of the elements in it's list in the correct order. Throws NullPointerException if the specified array is null.
import java.util.LinkedList;public class LinkedListDemo { public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); // Converting LinkedList to an Array
Object[] array = list.toArray(); } }
An LinkedList can be passed as an argument to another method like in below example.
import java.util.LinkedList;public class LinkedListDemo { public static void printLinkedList(final LinkedList<String> linkedList) { for (final String item : linkedList) { System.out.println(item); } } public static void main(final String[] args) { final LinkedList<String> list = new LinkedList<>(); list.add("Audi"); list.add("BMW"); list.add("Benz"); printLinkedList(list); } } Output: Audi BMW Benz
Here:I have a method to print LinkedList values that receives an LinkedList as an argument. This method does not create new LinkedList objects. So, this method can be reused whenever you want to print the values of an LinkedList. Thus you are reducing the redundant code.
No comments:
Post a Comment