Constructors and methods of LinkedList in Java

We have two constructors for LinkedList.

  1. LinkedList()
  2. LinkedList(Collection c)

LinkedList() –

No argumented constructor used to create LinkedList objects. There is no logic inside this constructor.

LinkedList(Collection c) –

This constructor having Collection as an argument. This is helpful if we want to convert any other collection classes into LinkedList. Let’s see an example where we will convert ArrayList to LinkedList and Vector to LinkedList.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ArrayListToLinkedList {
	public static void main(String[] args) {
		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");
		System.out.println("list of Arraylist -- " + listObject);

		// we have LinkedList(Collection c)
		List<String> listOfLinkedList = new LinkedList<>(listObject);
		System.out.println("list of LinkedList-- " + listOfLinkedList);
	}
}

Output is –

list of Arraylist — [ram, mohan, shyam, mohan, ram]
list of LinkedList– [ram, mohan, shyam, mohan, ram]

Similarly, we can convert Vector to LinkedList.

import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

public class VectorToLinkedList {
	public static void main(String[] args) {
		List<String> listOfVector = new Vector<>();

		listOfVector.add("ram");
		listOfVector.add("mohan");
		listOfVector.add("shyam");
		listOfVector.add("mohan");
		listOfVector.add("ram");
		System.out.println("list of Vector -- " + listOfVector);

		// we have LinkedList(Collection c)
		List<String> listOfLinkedList = new LinkedList<>(listOfVector);
		System.out.println("list of LinkedList-- " + listOfLinkedList);
	}
}

Output is –

list of Vector — [ram, mohan, shyam, mohan, ram]
list of LinkedList– [ram, mohan, shyam, mohan, ram]