Convert Array to LinkedList in Java
Array is contiguous memory allocation while LinkedList is a bloc of elements randomly placed in the memory which are linked together where a block is holding 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 enterprising world it becomes necessary to convert arrays to List. Here conversion of array to LinkedList is demonstrated.
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.
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.
- Create an array.
- Convert the array to List.
- Create LinkedList from the List using the constructor.
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.
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.
- 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.
Converted LinkeddList : [G, E, E, K, S]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.