In previous tutorials We have learn about LinkedList in java . We have given different java linkedlist example and explain about how to Linkedlist works , declaration of Linkedlist and difference between array and LinkedList . if you are new in Linkedlist then i recommended to you first read this article one LinkedList class in java . In this post we will learn about how can we create LinkedList in java. We have two constructor of LinkedList in java as following .
- LinkedList() – Constructs an empty list.
- LinkedList(Collection<? extends E> c) – Constructs a list containing the elements of the given collection, in the order they are returned by the collection’s iterator.
Now will create LinkedList using these constructor , Let’s see this by code.
import java.util.ArrayList;
import java.util.LinkedList;
public class CreateLinkList {
public static void main(String[] args) {
/*
* Constructs an empty list.
*/
LinkedList<String> linkedList = new LinkedList<String>();
//adding element in linkedlist
linkedList.add("PHP");
linkedList.add("JAVA");
linkedList.add("C++");
linkedList.add("Android");
//print linkedlist
System.out.println("Linklist is =" + linkedList);
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("sumsung");
arrayList.add("noika");
arrayList.add("spice");
/*
* Constructs a list containing the elements of the specified collection,
* in the order they are returned by the collection's iterator.
*/
LinkedList<String> linkedListFromCollection = new LinkedList<>(arrayList);
//print linkedlist
System.out.println("linkedlist is ="+ linkedListFromCollection);
}
}
Output :
Linklist is =[PHP, JAVA, C++, Android]
linkedlist is =[sumsung, noika, spice]
References