The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
The Java ArrayList toArray() method converts an arraylist into an array and returns it. The syntax of the toArray() method is: arraylist.toArray(T[] arr) Here, arraylist is an object of the ArrayList class.
To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set() method to update the replace the old element with new element. Find index of existing element using indexOf() method. Use set(index, object) to update new element.
Like this:
List<String> list = new ArrayList<String>();
String[] a = list.toArray(new String[0]);
Before Java6 it was recommended to write:
String[] a = list.toArray(new String[list.size()]);
because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
If your list is not properly typed you need to do a cast before calling toArray. Like this:
List l = new ArrayList<String>();
String[] a = ((List<String>)l).toArray(new String[l.size()]);
It doesn't really need to return Object[]
, for example:-
List<Custom> list = new ArrayList<Custom>();
list.add(new Custom(1));
list.add(new Custom(2));
Custom[] customs = new Custom[list.size()];
list.toArray(customs);
for (Custom custom : customs) {
System.out.println(custom);
}
Here's my Custom
class:-
public class Custom {
private int i;
public Custom(int i) {
this.i = i;
}
@Override
public String toString() {
return String.valueOf(i);
}
}
A shorter version of converting List to Array of specific type (for example Long):
Long[] myArray = myList.toArray(Long[]::new);
(available from java 11)
arrayList.toArray(new Custom[0]);
http://download.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28java.lang.Object[]%29
public static <E> E[] arrayListToTypedArray(List<E> list) {
if (list == null) {
return null;
}
int noItems = list.size();
if (noItems == 0) {
return null;
}
E[] listAsTypedArray;
E typeHelper = list.get(0);
try {
Object o = Array.newInstance(typeHelper.getClass(), noItems);
listAsTypedArray = (E[]) o;
for (int i = 0; i < noItems; i++) {
Array.set(listAsTypedArray, i, list.get(i));
}
} catch (Exception e) {
return null;
}
return listAsTypedArray;
}
I got the answer...this seems to be working perfectly fine
public int[] test ( int[]b )
{
ArrayList<Integer> l = new ArrayList<Integer>();
Object[] returnArrayObject = l.toArray();
int returnArray[] = new int[returnArrayObject.length];
for (int i = 0; i < returnArrayObject.length; i++){
returnArray[i] = (Integer) returnArrayObject[i];
}
return returnArray;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With