2

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?

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

That was quite and easy solution... But not as nice :)
Unfortunately, no nicer solution is available.
Wow, it's unbelievable that Java still doesn't have array auto-unboxing. BTW this answer is for a single dimension. The question is for 2D array, so it requires nested for loops. Crazy for something so simple.
2

With Guava: double[] Doubles.toArray(Collection<? extends Number) does the trick.

6 Comments

Wow, this is really useful mate! Just looked at it briefly and at first glance it seems like a library that makes up for java's mistakes and missing implementation. Anything similar you might know about btw?
I work on Guava. If you're curious about all the things Guava offers, the best place to start is the wiki.
Yeah looks good. Do you reckon this is the most complex suite ou there available?
Um. Not sure what you mean, but not using Guava would be like having a hand tied behind my back.
I was wondering if there are similar packages, perhaps targetting other issues with Java as well, I should know about
|
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.