How to Convert ArrayList to Array in Java?

0 Flares 0 Flares ×

While developing Java applications I have to convert ArrayList to Array lots of time. This is a very simple task and does not need any iterations, but I have seen most of the developers end up in iterating the list to create the array. So I thought of sharing this piece of code which converts ArrayList to Array in a single line.

ArrayList class has a method toArray() which can be used to convert to Array and here in this example we are using the same method.

Java Code to Convert ArrayList to Array

package com.lessonslab.util;

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

public class ConvertArrayListToArray
{
public static void main(String args[])
{
List<String> list = new ArrayList<String>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
list.add("Test4");
//toArray() adjusts the size automatically
//So you just need to initialize it with 0
String[] array = list.toArray(new String[0]);
//Print the array
System.out.println(Arrays.toString(array));
}
}

Output

[Test1, Test2, Test3, Test4]

To Generalise: To convert ArrayList of any class to Array use the below code. Just replace T with the class you want to create arrays.

T[] array = list.toArray(new T[0]);

This code will work for any kind of ArrayLists.

Guru

+Ayodhyanath Guru holds a B.Tech degree in Electrical Engineering and has worked with various prestigious clients in the IT industry and presently working as a Software Engineer. He is a part time blogger and presently authors the Jafaloo.Com blog. Being a tech enthusiast Guru likes to surf the web and blogs about interesting technical topics like How-To guides, freewares, Tutorials, Software, Gadgets, web applications etc. Apart from blogging he likes coding in Java/J2EE and PHP.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 0 Flares ×