Convert Array to LinkedList in Java
Array is contiguous memory allocation while LinkedList is a block of elements randomly placed in the memory which are linked together where a block is holding the address of another block in memory. Sometimes as per requirement or because of space issues in memory where there are bigger chunks of code in the enterprising world it becomes necessary to convert arrays to List. Here conversion of array to LinkedList is demonstrated.
Methods:
- Using asList() method of Collections class
- Using addAll() method of Collections class
Method 1: Using asList() method of Collections class
This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serialized and implements RandomAccess. This runs in O(1) time.
Syntax:
public static List asList(T... a) ;
Parameters: This method takes the array a which is required to be converted into a List. Here array of parameters works similar to an object array parameter.
Approach:
- Create an array.
- Convert the array to List.
- Create LinkedList from the List using the constructor.
Example
Java
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
String[] strArr = { "A" , "B" , "C" , "D" , "E" };
List<String> list = Arrays.asList(strArr);
LinkedList<String> linkedList
= new LinkedList<String>(list);
System.out.println( "LinkedList of above array : "
+ linkedList);
}
}
|
Output
LinkedList of above array : [A, B, C, D, E]
Method 2: Using addAll() method of Collections class
This method is used to append all the elements from the collection passed as parameter to this function to the end of a list keeping in mind the order of return by the collections iterator.
Syntax:
boolean addAll(Collection C) ;
Parameters: The parameter C is a collection of ArrayList. It is the collection whose elements are needed to be appended at the end of the list.
Return Value: The method returns true if at least one action of append is performed else return false.
Approach:
- Create an array.
- Create an empty LinkedList.
- Use addAll() method of collections class which takes two objects as parameters.
- First object as where to be converted
- Second object as which to be converted.
Example
Java
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class GFG {
public static void main(String[] args)
{
String[] strArr = { "G" , "E" , "E" , "K" , "S" };
LinkedList<String> linkedList
= new LinkedList<String>();
Collections.addAll(linkedList, strArr);
System.out.println( "Converted LinkedList : " +linkedList);
}
}
|
Output
Converted LinkedList : [G, E, E, K, S]
Last Updated :
31 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...