The ArrayList in Java is an index-based ordered collection, and LinkedList is a doubly linked list implementation in which each element in the list has a reference to the next and previous item in the list. An ArrayList is useful for storing the data items during the processing, and LinkedList is useful for scenarios where front and back List navigation is required.
In this tutorial, we will learn to convert LinkedList to ArrayList in Java with examples. We will also learn to convert ArrayList to LinkedList in Java.
1. Convert LinkedList to ArrayList
To convert a LinkedList containing objects to an ArrayList containing similar objects, we can use the arraylist constructor, which accepts another collection and initialize the arraylist with the elements of it.
We can pass the LinkedList instance to the constructor as follows:
LinkedList<String > linkedList = new LinkedList(); //add items linkedList.add("A"); linkedList.add("B"); linkedList.add("C"); linkedList.add("D"); ArrayList<String> arrayList = new ArrayList<>(linkedList); Assertions.assertEquals(4, arrayList.size());
We can also use the ArrayList.addAdd() method to populate an empty ArrayList with the elements from the LinkedList.
ArrayList<String> arrayList = new ArrayList<>(); arrayList.addAll(linkedList); Assertions.assertEquals(4, arrayList.size());
2. Convert ArrayList to LinkedList
The conversion from ArrayList to LinkedList is very similar to the previous examples. Here we have to use the LinkedList constructor. It accepts another collection and initializes the linkedlist with the elements of the arraylist.
ArrayList<String> arrayList = new ArrayList<>(); //add items LinkedList<String > linkedList = new LinkedList(arrayList);
The addMethod() can also be used for populating an empty initialized LinkedList with the items of the ArrayList.
LinkedList<String> linkedList = new LinkedList<>(); linkedList.addAll(arrayList);
Happy Learning !!