I am porting some Objective C code.
I need to create a list (I will use any type of list, whatever makes sense) of objects. The class looks like this:
class Foo{
double fooValue1;
double fooValue2;
double fooValue3;
double fooValue4;
}
I am reading a binary file into a byte array which works fine. The byte array is a list of
4 doubles. So if there are 100 instances of Foo in the file, the byte array has 3200 bytes. i.e. 4 * 8 * 100.
in Objective C, a variable is declared as a pointer to an array of type Foo. It is very fast to load that array by simply copying the bytes. The statement to do this is:
[byteArray getBytes:fooData range:range]
where range is an NSRange instance with location=0 and length=length of the byte array, byteArray is the raw byte[] read from the file and fooData is the pointer to the target array.
At the moment, I’m looping through the byte array, creating a new instance of Foo for each 32 bytes, then assigning the fields by converting each 8 bytes into doubles. For thousands of objects, this is slow.
I’m targeting API 8 so Arrays.copyOf is not available to me although if it offers a good solution, I would consider changing the target.
The question is; Is there a way to create a list in a similar “one statement” fashion to Objective C?
Thanks
[EDIT] Here’s the final code I used based on Peter’s answer. I should add that the file actually contains a list of lists, separated with headers. The result of parsing the file is an array of byte arrays.
ArrayList<SCGisPointData> pointData = new ArrayList<SCGisPointData>();
SCGisPointData thisPointdata;
for (byte[] ring : linearRings) {
DoubleBuffer buffer = ByteBuffer.wrap(ring).order(ByteOrder.nativeOrder()).asDoubleBuffer().asReadOnlyBuffer();
thisPointdata= new SCGisPointData ();
while (buffer.hasRemaining()) {
thisPointdata = new SCGisPointData();
thisPointdata.longitude = buffer.get();
thisPointdata.latitude = buffer.get();
thisPointdata.sinLatitude = buffer.get();
thisPointdata.cosLatitude = buffer.get();
pointData.add(thisPointdata);
}
}
There is no way in pure Java to magically assume one type can be turning into a different type. BTW You can do this in HotSpot using Unsafe but I don’t believe you can use that in Android which is perhaps for the best.
You can speed up translation by using a direct ByteBuffer with native byte ordering. This minimises the overhead, but is not as fast in Android as it is in HotSpot (as the later can turn these into intrinsic methods)
I would time how long this takes as an estimate
Note: this won’t run long enough to even be JITted to native code.
on HotSpot Java 7 prints