Convert ArrayList to Arrays in Java

A lot of time I have to convert ArrayList to Arrays in my Java program. Although this is a simple task, many people don’t know how to do this and end up in iterating the java.util.ArrayList to convert it into arrays. I saw such code in one of my friends work and I thought to share this so that people don’t end up writing easy thing in complicated way. ArrayList class has a method called toArray() that we are using in our example to convert it into Arrays. Following is simple code snippet that converts an array list of countries into string array.
List<String> list = new ArrayList<String>(); list.add("India"); list.add("Switzerland"); list.add("Italy"); list.add("France"); String [] countries = list.toArray(new String[list.size()]);
Code language: Java (java)
So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.
List<T> list = new ArrayList<T>(); T [] countries = list.toArray(new T[list.size()]);
Code language: Java (java)

Convert Array to ArrayList

We just saw how to convert ArrayList in Java to Arrays. But how to do the reverse? Well, following is the small code snippet that converts an Array to ArrayList:
import java.util.ArrayList; import java.util.List; import java.util.Arrays; ... String[] countries = {"India", "Switzerland", "Italy", "France"}; List list = Arrays.asList(countries); System.out.println("ArrayList of Countries:" + list);
Code language: Java (java)
The above code will work great. But list object is immutable. Thus you will not be able to add new values to it. In case you try to add new value to list, it will throw UnsupportedOperationException. Related: Resolve UnsupportedOperationException exception Thus simply create a new List from that object. See below:
String[] countries = {"India", "Switzerland", "Italy", "France"}; List list = new ArrayList(Arrays.asList(countries)); System.out.println("ArrayList of Countries:" + list);
Code language: Java (java)

View Comments

  • String[] countries = new String[0];

    List list = new ArrayList();
    list.add("India");
    list.add("Switzerland");
    list.add("Italy");
    list.add("France");

    countries = list.toArray(countries);

  • You don't have to put the list.size() to the new array, just 0 is enough because it just uses the information about the type of the return array, not the size, so the following code will work:
    T [] countries = list.toArray(new T[0]);

  • Maybe the following comment would have been better:

    This is also works: T[] countries = list.toArray(new T[0]);

    The \"toArray\" method automatically adjusts the size of the target array, but it must be initialized... I just use zero;

  • If you use an array with the correct size within the toArray method, the result is returned within the provided array. If you use a "new T[0]" another array has to be created, that is thrown away after the type information is read.
    So it is bad style to use "new T[0]".

  • If your code works then can you please explain this?

    Test.java:8: generic array creation
    T [] countries = list.toArray(new T[list.size()]);
    ^
    1 error

    • Instead of T in your code (because there is no such type) put any object type as you want, for example
      String [] countries = list.toArray(new String[list.size()]);
      It was kind of shortcoming. If you put code with T inside of generic method or class it will works.

  • Thank you for the great post.
    Maybe, it's too late to say this but anyway, let's try.
    About the Array to ArrayList conversion, I got error. It cannot recognize the Arrays type.
    Obviously, I imported the needed classes but even the NetBeans auto-complete couldn't help to find the reason of the error!
    By a little bit searching, I figured out that the following code works fine:

    String[] countries = {"India", "Switzerland", "Italy", "France"};
    ArrayList list = new ArrayList(Arrays.asList(countries));

    Thanks,
    Ahmad

  • This is good way to convert ArrayList to Array
    [code language="java"]
    //this is Generic
    ArrayList al = new ArrayList();
    al.add("Shakeel");
    al.add("Raj");

    //this is collection
    ArrayList al1 = new ArrayList();
    al1.add("Shakeel");
    al1.add("Shaan");
    al1.add("Shakeel");
    al1.add("Raj");

    //ArrayList to Array
    String ar[]=al.toArray(new String[al.size()]);
    ar=al.toArray(ar);
    for(int j=0;j&lt;ar.length;j++)
    {
    System.out.println(&quot;Element of ar &quot; + ar[j]);
    }
    System.out.println(&quot;&quot;);
    Object ar1[]=al1.toArray(new Object[al1.size()]);
    ar1=al1.toArray(ar1);
    for(Object e:ar1)
    System.out.println(&quot;Elements of ar1 &quot; +(String) e);
    [/code]

Share
Published by
Viral Patel
Tags: arraylists How-To Java java code java collections

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago