简体   繁体   中英

Java toArray() method: primitive result type

I am trying to do the following:

double[][] ret = new double[res.size()][columnSize];
for(int i = 0; i < res.size(); i++){
     ret[i] = res.get(i).toArray(new double[columnSize]);
}

where res is declared as List<List<Double>> . The above does not work because toArray() method wants a parametrized array to infer resulting type and that cannot be primitive...

Now, I could just change return type of my method to Double[][] but later on I have other functions from different APIs that expect double[][] 9primitives). That means there would be a lot of Upcasting, doesn't it?

ANy solutions, advices?

You cannot keep primitives in collections and you need to convert collections to array of primive types like this:

double[] toArray(Collection<Double> collection) {
    double[] arr = new double[collection.size()];
    int i = 0;
    for (Double d : collection) {
        arr[i++] = d;
    }
    return arr;
}

For 2D arrays.

private static int[][] convertListArray(ArrayList<Integer[]> al) {
    int[][] ret = new int[al.size()][];
    for (int i=0; i < al.size(); i++) {
        Integer[] row = al.get(i);
        ret[i] = new int[row.length];
        for (int j = 0; j < row.length; j++) {
            ret[i][j] = row[j];
        }
    }
    return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM