You can use the constructor of LinkedList
that accepts a Collection
, passing the ArrayList
as an argument.
ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("A"); arrayList.add("B"); // Convert ArrayList to LinkedList
LinkedList<String> linkedList = new LinkedList<>(arrayList);
How to convert a LinkedList to an ArrayList:
Similarly, use the constructor of ArrayList
that accepts a Collection
, passing the LinkedList
as an argument.
LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("X"); linkedList.add("Y"); // Convert LinkedList to ArrayList
ArrayList<String> arrayList = new ArrayList<>(linkedList);
Things to keep in mind:
1. The conversion is straightforward since both implement the List
interface.
2. Be aware of performance impacts if you're switching between these structures frequently for large datasets.