casting ArrayList.toArray() with ArrayList of Generic Arrays

前端 未结 3 1846
梦毁少年i
梦毁少年i 2021-02-06 03:10

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

3条回答
  •  梦毁少年i
    2021-02-06 03:50

    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]

提交回复
热议问题