Learn How java arrays is converted into list.
Learn How java arrays is converted into list.In this tutorial we are going to create array object and then convert it into the list object. Java Array provides a method asList() which is used to convert an array object into the list object.
When you call the asList() method on the object of array, it will create an instance of the list with the data from the array and returned into variable. You can assign this list object into a variable and use in your program.
In this program we are just printing the size of the list.
Example Code:
Code for converting array into list is:
list=Arrays.asList(ar);
Following is the complete code which is using the method asList() to convert
array into list object.
import java.util.*; public class array4 { public static void main(String[] args) { String ar[]={"aaa","bbb","ccc","ddd"}; Integer ar1[]={111,222,333,444}; List list=new ArrayList(); List list1=new ArrayList(); list=Arrays.asList(ar); list1=Arrays.asList(ar1); System.out.println(list.size()); System.out.println(list.get(2)); System.out.println(list); System.out.println("------------------\n"+list1.size()); System.out.println(list1.get(2)); System.out.println(list1); } }
Output:
4
ccc
[aaa, bbb, ccc, ddd]
------------------
4
333
[111, 222, 333, 444]
If you run the program it will display above output.
In this tutorial we have explained you the code for converting an array into list object. Following are more tutorials of arrays in Java: