Quantcast
Channel: Guru – Jafaloo – The Tech Blog
Viewing all articles
Browse latest Browse all 30

How to Convert Array to ArrayList in Java?

$
0
0

While writing Java applications we need to convert Array to ArrayList lots of time. Though the process is very simple and straightforward most of the developers end up in iterating the array to form the arraylist.

In this example we will be using Arrays.asList() method to convert the Array to ArrayList.

Java Example to Convert Array to ArrayList

package com.lessonslab.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConvertArrayToArrayList
{
public static void main(String args[])
{
String[] array = {"Test1","Test2","Test3","Test4"};
//Convert to ArrayList
List<String> arrayList = new ArrayList<String>(Arrays.asList(array));
//Lets print the ArrayList
System.out.println(arrayList.toString());
}
}

Output

[Test1, Test2, Test3, Test4]

To Generalise: To convert Array of any class to ArrayList you can use the below code. Replace T with the class of which you want to create the ArrayList.

List<T> arrayList = new ArrayList<T>(Arrays.asList(array));

The above code will work for any type of conversion.

The post How to Convert Array to ArrayList in Java? appeared first on Jafaloo - The Tech Blog.


Viewing all articles
Browse latest Browse all 30