How to Convert ArrayList to Array in Java

[1092 views]



In this article, we will learn how to convert ArrayList to Array in Java and write simple Program for it with and without toArray method.

What is ArrayList in Java?

ArrayList uses dynamic array to store data. ArrayList can change their size progressively. Components can be added and taken out from an ArrayList at whatever point there is a need, without worrying about initializing array size at the beginning.

  1. Java Program to Convert ArrayList to Array using toArray():
  2. import java.util.*; public class ArrayListWithToArray { public static void main(String args[]) { // create a ArrayList of String type ArrayList<String> words = new ArrayList<String>(); // Initialize an ArrayList with add() words.add("how"); words.add("are"); words.add("you"); // Convert ArrayList to Array String wordsArray[]=words.toArray(new String[words.size()]); // Printing wordsArray for(String word:wordsArray) System.out.println(word); } }

    Output:

    how are you

  3. Java Program to Convert ArrayList to Array without using toArray():
  4. import java.util.*; public class ArrayListWithoutToArray { public static void main(String args[]) { // create a ArrayList of String type ArrayList<String> words = new ArrayList<String>(); // Initialize an ArrayList with add() words.add("how"); words.add("are"); words.add("you"); // Convert ArrayList to Array String wordsArray[]=new String[words.size()]; for (int i = 0; i < words.size(); i++){ wordsArray[i]=words.get(i); } for(String word:wordsArray) System.out.println(word); } }

    Output:

    how are you
                 




Comments



Search

For any inquiry, Contact us at atechdailyweb@gmail.com




Facing Programming Errors. Get Answers within 24 hours:


Recommendation Based on your Interest




Quiz For You:
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    Simple Program for ArrayList to Array Conversion Java