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
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
to a T[]
, you'll need a T typeVar
,
To fix it:
public static T[] unTreeArray(T[][] input) {
java.util.List outList = new ArrayList();
java.util.List 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]