Então, normalmente ArrayList.toArray()
retornaria um tipo de Object[]
.... mas supostamente é um
Arraylist
objeto Custom
, como faço toArray()
para retornar um tipo de, Custom[]
e não Object[]
?
Então, normalmente ArrayList.toArray()
retornaria um tipo de Object[]
.... mas supostamente é um
Arraylist
objeto Custom
, como faço toArray()
para retornar um tipo de, Custom[]
e não Object[]
?
Respostas:
Como isso:
List<String> list = new ArrayList<String>();
String[] a = list.toArray(new String[0]);
Antes do Java6, era recomendável escrever:
String[] a = list.toArray(new String[list.size()]);
porque a implementação interna realocaria uma matriz de tamanho adequado de qualquer maneira, portanto, seria melhor fazê-lo antecipadamente. Como Java6, a matriz vazia é preferida, consulte .toArray (nova MyClass [0]) ou .toArray (nova MyClass [myList.size ()])?
Se sua lista não for digitada corretamente, você precisará fazer uma conversão antes de ligar para o Arrray. Como isso:
List l = new ArrayList<String>();
String[] a = ((List<String>)l).toArray(new String[l.size()]);
Realmente não precisa retornar Object[]
, por exemplo: -
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);
}
Aqui está a minha Custom
turma: -
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]);
Eu recebi a resposta ... isso parece estar funcionando perfeitamente bem
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;
}
Amostras:
String[] s = arrayListToArray(stringList);
Long[] l = arrayListToArray(longList);