Java : Converting ArrayList to Array and Array to ArrayList

arraylist to array

Converting an ArrayList to an Array

 
While working with ArrayList, we may need to get the actual array from it for several reasons :
 
– An existing method may require you to pass an array, but you have an arraylist instead
 
– Accessing elements from an array is faster compared to arraylist
 
– You may want to store user inputs in an array, but not sure of the number of entries.
 
 
We can get the underlying array using one of the following arraylist methods :
 

Object[] toArray()


 
This method returns an array containing all of the elements in the list in proper sequence (from first to last element).
 

T[] toArray(T[] a)


 
This form is more convenient than the first form since it returns a proper type array rather than generic object array.
 

This method returns an array containing all of the elements in the list in proper sequence (from first to last element). Here, the run-time type of the returned array is that of the specified array.
 

Example of converting an ArrayList to Array

 
In the below program, we are creating an ArrayList of Strings and then using toArray() method to convert it to an array.
 

package com.topjavatutorial;

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

public class ArrayListToArray {

  public static void main(String[] args) {

    List<Integer> numbers = new ArrayList<Integer>();
    
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    
    Integer[] arr = new Integer[numbers.size()];
        
    arr = numbers.toArray(arr);
    
    int sum =0;
    for(int num:arr){
      sum += num;
    }
    
    System.out.println("Sum = " + sum);
  }

}


 

Converting an Array to ArrayList

 
asList() method in Arrays class can be used to create a fixed-size arraylist from an array.
 

    List<Integer> list = new ArrayList<Integer>();
    
    Integer[] arr = {2,10,3};
    
    list = Arrays.asList(arr);
    
    System.out.println(list);

 
Running this program will print the arraylist elements as:
[2, 10, 3]
 
 
Here is a puzzle on Arrays.asList() that you may like :
 
Java Quiz 38 (Creating ArrayList from an Array)

 

You may also like :

 

© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

2 comments

  1. Nice tricks for convert ArrayList to Array ,Thanks for sharing such good information , Java Vogue have also shared good article on ararylsit visit a A Guide to arraylist

  2. […] Converting ArrayList to Array & Vice versa     […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: