Hey, I was trying to combine several arrays of type double into one single array, what is the best way to do it? Thanks!
+4
A:
- Create an array of the right size (by going through and summing the lengths of all the source arrays)
- Repeatedly call
System.arraycopy
to copy one source array at a time into the target array, updating the place where you copy it to on each iteration.
So something like:
public static double[] Combine(double[][] arrays)
{
int totalLength = 0;
for (double[] source : arrays)
{
totalLength += source.length;
}
double[] ret = new double[totalLength];
int index = 0;
for (double[] source : arrays)
{
System.arraycopy(source, 0, ret, index, source.length);
index += source.length;
}
return ret;
}
Jon Skeet
2009-11-11 15:57:13
I smell integer overflow!
erickson
2009-11-11 15:59:28
Wouldn't an overflow only occur if there's about 16 GB of data?
JRL
2009-11-11 16:08:45
Never underestimate the constraints on your inputs: http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
Andrzej Doyle
2009-11-11 16:16:45
Do you mean overflow of the totalLength?
Thomas Jung
2009-11-11 16:26:52
Well, I was just kidding, but yes, you'd need 16 GB of doubles to overflow. However, I'm sure that there are applications that do. I think one of the improvements for JDK 7 is arrays with a `long` length.
erickson
2009-11-11 16:28:05
This feature was dropped. Would check it anyway -> http://en.wikipedia.org/wiki/Ariane_5_Flight_501
Thomas Jung
2009-11-11 16:30:17
+1
A:
You can use this method from the Guava library, which is open-source and will have an actual binary release probably later this month: Doubles.concat(double[]...)
Kevin Bourrillion
2009-11-11 20:17:04