开发者

Conversion from Vector<double[]> to double[][]

开发者 https://www.devze.com 2023-02-28 18:26 出处:网络
How can I convert Vector&开发者_JS百科lt;double[]> to double[][] in java ?You can convert a Vector to an array by Vector.toArray():

How can I convert Vector&开发者_JS百科lt;double[]> to double[][] in java ?


You can convert a Vector to an array by Vector.toArray():

double[][] array = vector.toArray(new double[0][]);

This maybe slightly faster then for loop, because Vector can utilize System.arraycopy() on its internal array.


This will do it:

double matrix[][] = new double[vector.size()][];
for (int i = 0; i < vector.size(); i++) {
    matrix[i] = vector.get(i);
}

Note that this references the same double[] arrays as in your Vector<double[]>. So a change in that will be reflected in the new matrix[][]. If you don't want that then you'll have to create a new double[] for each iteration and copy the values from the old array to the new array.


Muhammed,

WhiteFang is correct... if you're looking for an "out of the box" solution then have a look at Apache's Commons Collections (http://commons.apache.org/collections/)

It's been over a year since I touched Java, but if I recall correctly, "commons" has converters for Vectors... as well as many, many, many other handy bits of kit.

And BTW: If using a Vector is your choice, and you don't have a good reason to NOT use an ArrayList, then use an ArrayList... It's slightly quicker. Except it's NOT threadsafe; whereas all Vectors methods are syncronised. Explanation here: http://skeletoncoder.blogspot.com/2006/09/java-tutorials-arraylist-or-vector.html.

Cheers. Keith.

0

精彩评论

暂无评论...
验证码 换一张
取 消