Can ArrayList be converted to list?

  1. HowTo
  2. Java Howtos
  3. Convert List to ArrayList in Java

Convert List to ArrayList in Java

Java Java List Java ArrayList

Created: October-06, 2021 | Updated: November-08, 2021

In this guide, we have talked about how you can convert a list to an ArrayList in Java. But before we go into it, you should be familiar with some of the basic concepts in Java. You need to understand that list is implemented by the Interface Collection, and ArrayList is an implemented class of List.

Converting List to ArrayList in Java

Lets take a look at the example down below.

import java.util.*; public class Hello { public static void main[String[] args] { //Let's make a List first. List MyList = [List] Arrays.asList["Hello","World"]; } }

The above List contains two string elements, as you can see. Here, Arrays.asList is a static method used to convert an array of objects into a List. Lets see how we can have this List convert into an ArrayList.

Learn more about Array Class here.

import java.util.*; public class Hello { public static void main[String[] args] { //Let's make a List first. List MyList = [List] Arrays.asList["Hello","World"]; ArrayList a1 = new ArrayList[MyList]; } }

With this approach, we are actually initializing the ArrayList featuring its predefined values. We simply made a list with two elements using the Arrays.asList static method. Later we used the constructor of the ArrayList and instantiated it with predefined values. Learn more about ArrayList and its methods and other properties.

In other words, we had an array with elements in it and converted it into List and later turned that list into an ArrayList. Take a look at the example down below for understanding whats happening.

import java.util.*; public class Hello { public static void main[String[] args] { String arr[]={"1","2","3"}; List MyList = [List] Arrays.asList[arr]; //now we are converting list into arraylist ArrayList a1 = new ArrayList[MyList]; for[int i=0; i

Chủ Đề