Convert ArrayList to Array in Java

In this tutorial, you will learn how to convert ArrayList to an Array in Java using two methods:

  • Using a for loop – I will show you how to use a ‘for loop’ to go through an ArrayList and move everything over to an Array. It’s like packing your things into a new suitcase one item at a time. It’ll help you understand how Java works and how you can organize your information.
  • Using ArrayList.toArray() method – This is like having a magic wand that does the packing for you. It’s faster, and it’s great to know how to use the shortcuts Java gives us.

Convert ArrayList to Array in Java with a for loop

In this example, we create an empty array, then iterate over the list and add each element to the array.

class Test {

  public static void main(String[] args) {

    List<String> list = new ArrayList<>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    list.add("item4");

    // create an empty array with length == size of the list
    String[] array = new String[list.size()];

    // iterate over a list and add each element to the array
    for (int i = 0; i < list.size(); i++) {
      array[i] = list.get(i);
    }

    // print array elements
    System.out.println(Arrays.toString(array));
  }
}
Output: [item1, item2, item3, item4]

Convert list to array using ArrayList.toArray() method

Instead of copying each element of the list manually to the array, like in the above example, we can use the ArrayList.toArray() method that converts the list to an array.

Example

class Test {

  public static void main(String[] args) {

    List<String> list = new ArrayList<>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    list.add("item4");

    // convert ArrayList to array
    String[] array = list.toArray(new String[list.size()]);

    // print array elements
    System.out.println(Arrays.toString(array));
  }
}
Output: [item1, item2, item3, item4]
 
And that’s it! If you want to learn how to convert an array to a list, check out this post.
 
Happy coding!

Leave a Reply

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