Entonces, normalmente ArrayList.toArray()devolvería un tipo de Object[]... pero supongo que es un
Arraylistobjeto Custom, ¿cómo hago toArray()para devolver un tipo de en Custom[]lugar de Object[]?
Entonces, normalmente ArrayList.toArray()devolvería un tipo de Object[]... pero supongo que es un
Arraylistobjeto Custom, ¿cómo hago toArray()para devolver un tipo de en Custom[]lugar de Object[]?
Respuestas:
Me gusta esto:
List<String> list = new ArrayList<String>();
String[] a = list.toArray(new String[0]);
Antes de Java6 se recomendaba escribir:
String[] a = list.toArray(new String[list.size()]);
porque la implementación interna reasignaría una matriz del tamaño adecuado de todos modos, por lo que sería mejor hacerlo por adelantado. Como Java6 se prefiere la matriz vacía, vea .toArray (nueva MyClass [0]) o .toArray (nueva MyClass [myList.size ()])?
Si su lista no está escrita correctamente, debe hacer un reparto antes de llamar a Array. Me gusta esto:
List l = new ArrayList<String>();
String[] a = ((List<String>)l).toArray(new String[l.size()]);
Realmente no necesita regresar Object[], por ejemplo: -
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);
}
Aquí está mi Customclase: -
public class Custom {
private int i;
public Custom(int i) {
this.i = i;
}
@Override
public String toString() {
return String.valueOf(i);
}
}
arrayList.toArray(new Custom[0]);
Recibí la respuesta ... esto parece estar funcionando perfectamente bien
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;
}
@SuppressWarnings("unchecked")
public static <E> E[] arrayListToArray(ArrayList<E> list)
{
int s;
if(list == null || (s = list.size())<1)
return null;
E[] temp;
E typeHelper = list.get(0);
try
{
Object o = Array.newInstance(typeHelper.getClass(), s);
temp = (E[]) o;
for (int i = 0; i < list.size(); i++)
Array.set(temp, i, list.get(i));
}
catch (Exception e)
{return null;}
return temp;
}
Muestras:
String[] s = arrayListToArray(stringList);
Long[] l = arrayListToArray(longList);