Collection-3 || LinkedList Class implementation and usage.

In LinkedList objects are stored as a node in a List. Each node is divided in three parts: Address of Previous node, Data of the node, Address of Next node.

Review features of ArrayList

  • It is a resizable array which increases the array size whenever we add new items in the list. The default size of ArrayList is 10.
  • Use ArrayList if you want to add remove data from the end.
  • ArrayList is slow to add or remove elements as it moves each element one unit up or down in the entire list.
  • Faster to traverse the List
  • The behavior is the same as the normal array and all the elements placed as a stack.
  • While traverse using Iterator ‘null’ value throws an exception.

Keypoints in LinkedList

Structure of LinkedList.
  • Class: LinkedList
  • Interface: List
  • Package: java.util
  • LinkedList uses the traditional method where it has a Head, Nodes, Tail.
  • It creates a new Node for each item added to the list.
  • Allows Null and duplicate values into the list.
  • A Node divided into three parts Previous Node Ref, Element value, Next Node Ref
  • Use this if you want to add remove data in-between the list.
  • Each element has a reference of next and prev node
  • Faster to add/remove elements as it just needs to change the reference for the element around it.
  • Slow to traverse the list.
  • While traverse using Iterator ‘null’ value doesn’t throw an exception.

Declaration of LinkedList

List<String> tempList = new LinkedList<String>();
List<Integer> tempList = new LinkedList<Integer>();
List mixedArray=new LinkedList<>();

Adding values into the LinkedList objects

We can add elements in the LinkedList object using add() method similar to ArrayList. It allows null as well as duplicate values in the list.

// Declaration of LinkedList
		LinkedList<String> list1=new LinkedList<String>();		
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");

Data manipulation in LinkedList object

In this section will learn about basic operations and methods of LinkedList Objects.

  • Access Head or first element and Last element of the LinkedList using below two methods
    • list1.element()
    • list1.getFirst()
    • list1.getLast()
  • Traversing of List using a for-each loop
  • Traversing of List using Iterator
  • Adding null value is allowed but it will throw an exception while traversing using the Iterator.
  • Getting the total number of items using size()
  • Getting index value based on the item value using indexOf(Object)
  • Accessing any item using the index key and get(index)
  • Add new data at the end of the list using add()
  • Adding data using index key in add(index, value)
  • Removing specific data using the index or value using the below methods:
    • remove() : Return and remove the head(first element)
    • remove(int index) : Remove and return specific element by index
    • remove(Object value) : Remove element by value and return boolean value
    • removeFirst() : Remove and returns First Element
    • removeLast() : Remove and returns Last Element
  • Removing items using a reference of other list using removeAll(Collection)
  • Remove all elements in the list using the clear() method.
  • Searching value or list using contains() and containsAll()

Access Head or first element

// Declaration of LinkedList
		LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
		
		System.out.println(list1);
	// Returns the head (first element) in the linkedlist.
		System.out.println("Head: "+list1.element());
		System.out.println("FirstElement: "+list1.getFirst());
      // Returns last element in the list
		System.out.println("Last Element: "+list1.getLast());
------------------------------------------------------------------------------
Output:
[Languages, Java, C#, C++, Selenium, null, Java]
Head: Languages
FirstElement: Languages
Last Element: Java

Traversing of List using a for-each loop

// Declaration of LinkedList
		LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
System.out.println("\nTraversing linkedList using for-each Loop:");
		for (String string : list1) 
		{
			System.out.println(string);
		}
------------------------------------------------------------------------------
Output:
Traversing linkedList using for-each Loop:
Java
C++
null
Java
C#
Appium

Traversing of List using Iterator

Here we are taking the mixed type of LinkedList just for a change.

// Mixed data type LinkedList
		List list2=new LinkedList<>();
		list2.add("Java");
		list2.add(20);
		list2.add(null);
		list2.add('c');
		list2.add(null);
		list2.add(3.4);
	
System.out.println("\nTraversing the LinkedList using Iterator Interface:");
		Iterator iterator=list2.iterator();
		while(iterator.hasNext())
		{
			System.out.println(iterator.next());
		}
------------------------------------------------------------------------------
Output:
Traversing the LinkedList using Iterator Interface:
Java
20
null
c
null
3.4

Getting the total number of items using size()

LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
		
		System.out.println(list1);
		System.out.println("Size of LinkedList: "+list1.size());
------------------------------------------------------------------------------
Output:
[Languages, Java, C#, C++, Selenium, null, Java]
Size of LinkedList: 7

Getting index value based on the item value using indexOf(Object)

LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
		
		System.out.println(list1);
		System.out.println("Index of element: "+list1.indexOf("C++"));
------------------------------------------------------------------------------
Output
[Languages, Java, C#, C++, Selenium, null, Java]
Index of element: 3

Accessing any item using the index key and get(index)

LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
		
		System.out.println(list1);
		System.out.println("Value of element at index: "+list1.get(4));
------------------------------------------------------------------------------
Output:
[Languages, Java, C#, C++, Selenium, null, Java]
Value of element at index: Selenium

Adding data using index key in add(index, value)

At the starting of this chapter, we have seen that when we use add() method it appends the element at the end of the LinkedList. However, there may be a requirement to insert values in-between the linked list. For this, we could use the add(index, value) method. This method inserts the value at a given index in the list.

// Declaration of LinkedList
		LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
		
		System.out.println(list1);
	//Adding new data to the specific position in LinkedList
	list1.add(4, "Python");
	System.out.println("After inserting new value at given Index : \n"+list1);
------------------------------------------------------------------------------
Output:
[Languages, Java, C#, C++, Selenium, null, Java]
After inserting new value at given Index :
[Languages, Java, C#, C++, Python, Selenium, null, Java]				

Removing specific data using the index or value

Important and basic methods in this category are mentioned below:

  • remove() : Return and remove the head(first element)
  • remove(int index) : Remove and return specific element by index
  • remove(Object value) : Remove element by value and return boolean value
  • removeFirst() : Remove and returns First Element
  • removeLast() : Remove and returns Last Element
// Declaration of LinkedList
		LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Python");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
            System.out.println("\nOriginal List: \n"+list1);
		
		// Return and remove the head(first element) in the list.
		System.out.println("\nRemoved Head: "+list1.remove());
		System.out.println("After removing head:\n"+list1);
		System.out.println("New Head: "+list1.element());
				
		// Remove and return specific element by index value
		System.out.println("\nRemoved by Index: "+list1.remove(2));
		System.out.println("After removing by 'index' :\n"+list1);
		
		//Remove element by value and return boolean value
	System.out.println("\nRemoved by Value: "+list1.remove("Selenium"));
	System.out.println("After removing element by 'value' :\n"+list1);
		
		// Remove and returns First Element in the list
	System.out.println("\nRemoved first element: "+list1.removeFirst());
		System.out.println("After Removing first element: \n"+list1);
		
		// Remove and returns Last Element in the list
	System.out.println("\nRemoved Last element: "+list1.removeLast());
		System.out.println("After removing last element: \n"+list1);
-------------------------------------------------------------------------
Output:
Original List: 
[Languages, Java, C#, C++, Python, Selenium, null, Java]

Removed Head: Languages
After removing head:
[Java, C#, C++, Python, Selenium, null, Java]
New Head: Java

Removed by Index: C++
After removing by 'index' :
[Java, C#, Python, Selenium, null, Java]

Removed by Value: true
After removing element by 'value' :
[Java, C#, Python, null, Java]

Removed first element: Java
After Removing first element: 
[C#, Python, null, Java]

Removed Last element: Java
After removing last element: 
[C#, Python, null]

Removing items using a reference of other list using removeAll(Collection)

// Declaration of LinkedList
		LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");
                System.out.println("Values in list1:\n"+list1);
		System.out.println("Values in list2:\n"+list2);
	System.out.println("Removing values from list1 with reference to list2");
		System.out.println("Items removed: "+list1.removeAll(list2));
		System.out.println("\nRemaining items in list1:\n"+list1);
------------------------------------------------------------------------------
Output:
Values in list1:
[Languages, Java, C#, C++, Selenium, null, Java]
Values in list2:
[Java, 20, null, c, null, 3.4]
Removing values from list1 with reference to list2
Items removed: true

Remaining items in list1:
[Languages, C#, C++, Selenium]

Remove all elements in the list using the clear() method

// Declaration of LinkedList
		LinkedList<String> list1=new LinkedList<String>();
		list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");

                System.out.println("Values in list1:\n"+list1);
                list1.clear();
		System.out.println("After removing all elements: "+list1);
------------------------------------------------------------------------------
Output:
Values in list1:
[Languages, Java, C#, C++, Selenium, null, Java]
After removing all elements: []

Searching value or list using contains() and containsAll()

These methods return boolean result True if the target value present in the list. Else, it returns False.

List list2=new LinkedList<>();
		list2.add("Java");
		list2.add(20);
		list2.add(null);
		list2.add('c');
		list2.add(null);
		list2.add(3.4);
		
                System.out.println("Result if target value '3.4' present in list: "+list2.contains(3.4));
		System.out.println("Result if target value 'ABC' not present: "+list2.contains("ABC"));
		System.out.println("\nResult of this method is case sensitive:-");
		System.out.println("Result for 'java' : "+list2.contains("java"));
		System.out.println("Result for 'Java' : "+list2.contains("Java"));
-----------------------------------------------------------------------------
Output:
Result if target value '3.4' present in list: true
Result if target value 'ABC' not present: false

Result of this method is case sensitive:-
Result for 'java' : false
Result for 'Java' : true

Searching another list using containsAll()

containsAll(anotherList) used to map and validated that all the items of ‘anotherList’ is present in the main. While searching it keeps two things for validation:

  • Item values are the case sensitive, so ‘A’ and ‘a’ will result in false.
  • The position or index of the values doesn’t matter.
LinkedList<String> list1=new LinkedList<String>();               
                list1.add("Languages");
		list1.add("Java");
		list1.add("C#");
		list1.add("C++");
		list1.add("Selenium");
		list1.add(null);
		list1.add("Java");

List list2=new LinkedList<>();
		list2.add("Java");
		list2.add(20);
		list2.add(null);
		list2.add('c');
		list2.add(null);
		list2.add(3.4);

List list3=new LinkedList<>();
		list3.add("C#");
		list3.add(null);
		list3.add("Languages");

// Returns true/false based on other list using containsAll()
System.out.println("list1 v/s list2 result: "+list1.containsAll(list2));
System.out.println("list1 v/s list3 result: "+list1.containsAll(list3));
----------------------------------------------------------------------------
Output:
list1 v/s list2 result: false
list1 v/s list3 result: true

604total visits,1visits today

Leave a Reply

Your email address will not be published. Required fields are marked *