Convert an ArrayList to an object array
Is there a command in java for conversion of an ArrayList into a object array. I know how to do this copying each object from the arrayList into the object array, but I was wondering if would it be done automatically. I want something like this:
ArrayList a; // Let's imagine "a" was filled with TypeA objects TypeA[] array = MagicalCommand(a);
6 Answers 6
Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection ):
TypeA[] array = a.toArray(new TypeA[a.size()]);
On a side note, you should consider defining a to be of type List rather than ArrayList , this avoid some implementation specific definition that may not really be applicable for your application.
Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])
ArrayList a = new ArrayList(); Object[] o = a.toArray();
Then if you want that to get that object back into TypeA just check it with instanceOf method.
Yes. ArrayList has a toArray() method.
Doesn’t work when printing though. It only prints the object address: System.out.println(Arrays.toString(itemsList.toArray()));
Convert an ArrayList to an object array
ArrayList has a constructor that takes a Collection, so the common idiom is:
List list = new ArrayList(Arrays.asList(array));
Which constructs a copy of the list created by the array.
now, Arrays.asList(array) will wrap the array, so changes to the list will affect the array, and visa versa. Although you can’t add or remove
elements from such a list.
TypeA[] array = (TypeA[]) a.toArray();
List
/** * Autores: Chalo Mejia * Fecha: 01/10/2020 */ package org.main; import java.io.Serializable; public class TestNovedad implements Serializable < private static final long serialVersionUID = -6362794385792247263L; private int id; private int cantidad; public TestNovedad() < // TODO Auto-generated constructor stub >public int getId() < return id; >public void setId(int id) < this.id = id; >public int getCantidad() < return cantidad; >public void setCantidad(int cantidad) < this.cantidad = cantidad; >@Override public String toString() < return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]"; >>
Java ArrayList.toArray()
Learn to convert ArrayList to an array using toArray() method. The toArray() method returns an array that contains all elements from the list – in sequence (from first to last element in the list).
ArrayList list = . ; Object[] array = list.toArray(); //1 String[] array = list.toArray(new String[list.size()]); //2
The toArray() is an overloaded method:
public Object[] toArray(); public T[] toArray(T[] a);
- The first method does not accept any argument and returns the Object[]. We must iterate the array to find the desired element and cast it to the desired type.
- In second method, the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. After filling all array elements, if there is more space left in array then ‘null’ is populated in all those spare positions.
2. ArrayList toArray() Examples
Java program to convert an ArrayList to Object[] and iterate through array content.
ArrayList list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); //Convert to object array Object[] array = list.toArray(); //Iterate and convert to desired type for(Object o : array) < String s = (String) o; //This casting is required System.out.println(s); >
Java program to convert an ArrayList to String[].
ArrayList list = new ArrayList<>(2); list.add("A"); list.add("B"); list.add("C"); list.add("D"); String[] array = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(array));
From Arraylist to Array
I want to know if it is safe/advisable to convert from ArrayList to Array? I have a text file with each line a string:
I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that? thanks
You can, but you haven’t given us nearly enough information to tell you whether it’s a good idea or not.
ArrayLists’s are fine. The only reason I can see for converting to an Array is if you need to call a method that requires it.
11 Answers 11
Yes it is safe to convert an ArrayList to an Array . Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList . Else convert away!
ArrayList foo = new ArrayList(); foo.add(1); foo.add(1); foo.add(2); foo.add(3); foo.add(5); Integer[] bar = foo.toArray(new Integer[foo.size()]); System.out.println("bar.length mt24">)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share)" title="">Improve this answer)">edited Oct 23, 2014 at 18:28 lgvalle3,7121 gold badge19 silver badges14 bronze badgesanswered Nov 1, 2011 at 15:50 ObscureRobotObscureRobot7,3062 gold badges27 silver badges36 bronze badges