A difficult question which I\'m close to giving up all hope on. I\'m trying to make a
function, but am having problems getting ArrayList.toArray()
to return the ty
toArray() always returns an object array.
To return an array of a specific type, you need to use toArray(Object[]).
To provide the correct type for the array argument, you need to use the specific class or in this case use reflections.
try
return (T[]) list.toArray(Array.newInstance(one.getClass(), list.size()));
The problem on your second code sample is caused because of your T[] typeVar
: Input is a two dim array, so input[0]
will return a one dim array (a String[], instead a String, as expected).
If your are to convert your List<T>
to a T[]
, you'll need a T typeVar
,
To fix it:
public static <T> T[] unTreeArray(T[][] input) {
java.util.List<T> outList = new ArrayList<T>();
java.util.List<T> tempList;
if (input.length == 0) {
return null;
}
T typeVar=null;
for (T[] subArray : input) {
if(typeVar==null && subArray.length>0) {
typeVar=subArray[0];
}
tempList = java.util.Arrays.asList(subArray);
outList.addAll(tempList);
}
return outList.toArray((T[]) Array.newInstance(typeVar.getClass(),0));
}
public static void main(String[] args) {
String[][] lines = { { "111", "122", "133" }, { "211", "222", "233" } };
String[] result=unTreeArray(lines);
System.out.println(result);
System.out.println(result.getClass());
//added for completion:
System.out.println( Arrays.toString(result));
}
The resulting output:
[Ljava.lang.String;@5a405a4 class
[Ljava.lang.String;
[111, 122, 133, 211, 222, 233]
You can't create an array of a generic type parameter. The simple reason is the fact that java usually erases the generic type information at runtime so the runtime has no idea what T is (when T is a generic type parameter).
So the solution is to actually get a hold of the type information at runtime. Usually this is done by passing around a Class<T> type
parameter but in this case you can avoid that:
@peter's answer looks good and i would use it :).
return (T[]) list.toArray(Array.newInstance(one.getClass(), list.size()));