Java arraylist to toarray

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 testNovedads = crudService.createNativeQuery( "SELECT cantidad, id FROM NOVEDADES GROUP BY id "); Gson gson = new Gson(); String json = gson.toJson(new TestNovedad()); JSONObject jsonObject = new JSONObject(json); Collection novedads = new ArrayList<>(); for (Object[] object : testNovedads) < Iteratoriterator = jsonObject.keys(); int pos = 0; for (Iterator i = iterator; i.hasNext();) < jsonObject.put((String) i.next(), object[pos++]); >novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class)); > for (TestNovedad testNovedad : novedads)
 /** * 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
lgvalle
3,7121 gold badge19 silver badges14 bronze badges
answered Nov 1, 2011 at 15:50
3
    What if ArrayList is empty?
    – ThanosFisherman
    Dec 10, 2015 at 2:54
    1
    The method toArray(T[]) in the type ArrayList is not applicable for the arguments (char[])
    – Aaron Franke
    Apr 2, 2018 at 4:28
    @AaronFranke You are trying to convert non primitive Character to primitive char. In java all arrays are created equal EXCEPT primitive ones. Maybe create and copy the array by hand in a for loop, OR if you like streams you can map to char and then call toCharArray on the stream
    – DownloadPizza
    Aug 22, 2022 at 6:26
Add a comment|
75

This is the best way (IMHO).

List myArrayList = new ArrayList(); //. String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);
String[] myArray = myArrayList.toArray(new String[0]); 

But it less effective: the string array is created twice: first time zero-length array is created, then the real-size array is created, filled and returned. So, if since you know the needed size (from list.size() ) you should create array that is big enough to put all elements. In this case it is not re-allocated.

ArrayList myArrayList = new ArrayList(); . String[] myArray = myArrayList.toArray(new String[0]); 

Whether it's a "good idea" would really be dependent on your use case.

JavaDocs are your friend. If the array being passed in is too small a new array is returned. The other version of the method that takes no args returns an array of Object

assuming v is a ArrayList:

String[] x = (String[]) v.toArray(new String[0]); 

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()]) ) or using an empty array (like c.toArray(new String[0]) ). In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation. You can follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

Источник

Converting ArrayList to Array in java

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:

String dsf[] = new String[al.size()]; for(int i =0;i

12 Answers 12

You don't need to reinvent the wheel, here's the toArray() method:

String []dsf = new String[al.size()]; al.toArray(dsf); 

There's also this form 'docs.oracle.com/javase/1.5.0/docs/api/java/util/…' for where you want to provide a specificly typed array.

List list=new ArrayList(); list.add("sravan"); list.add("vasu"); list.add("raki"); String names[]=list.toArray(new String[list.size()]) 
List list=new ArrayList(); list.add("sravan"); list.add("vasu"); list.add("raki"); String names[]=list.toArray(new String[0]); 

if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.

import java.util.*; public class arrayList < public static void main(String[] args) < Scanner sc=new Scanner(System.in); ArrayListx=new ArrayList<>(); //inserting element x.add(sc.next()); x.add(sc.next()); x.add(sc.next()); x.add(sc.next()); x.add(sc.next()); //to show element System.out.println(x); //converting arraylist to stringarray String[]a=x.toArray(new String[x.size()]); for(String s:a) System.out.print(s+" "); > > 
String[] values = new String[arrayList.size()]; for (int i = 0; i

What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29

Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:

What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.

Источник

Читайте также:  Php обмен данными между скриптами
Оцените статью