make arrayList.toArray () devuelve tipos más específicos

189

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[]?

kamikaze_pilot
fuente
1
Hay 2 métodos con el mismo nombre 'toArray ()' en ArrayList. A partir de 1.5, el segundo método toma una matriz escrita. ¿Estás buscando una solución para pre-1.5?
Ritesh

Respuestas:

308

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()]);
Mihai Toader
fuente
1
AFAIK: Esto tiene algo que ver con Java en su conjunto, al no poder usar constructores genéricos. Entonces, aunque sabe que lo necesita para convertirlo en un objeto como String [] o MyObject [], no puede crear una instancia por sí mismo.
¿Qué pasa si en lugar de String queremos usar double? Parece que falla ... Podemos usar Doble, pero ¿qué pasa si quiero doble?
Pixel
2
@pbs No puedes. Los genéricos de Java solo admiten tipos de referencia, no primitivos. Sin embargo, el auto-boxing / unboxing debería permitirle ignorar la diferencia entre ellos en su mayor parte.
solarshado
16

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);
    }
}
limc
fuente
1

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;
}
Ashvitha
fuente
0
@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);
Ali Bagheri
fuente
1
¿Qué pasa si tenemos ArrayList <Animal> y contiene tipos de perros y gatos que extienden Animal? Parece que fallaría si el primer elemento es Perro y el siguiente es Gato. Ve el primer elemento, crea una matriz de tipo Perro, agrega el perro, luego intenta agregar el gato y falla. También puede no funcionar con genéricos E.
ptoinson