I am very new to Java and its collections and I'm trying to figure out "best" way to populate an ArrayList<Byte>
in Java. In particular, I'm trying to take a 32 bit number, divide it into bytes, and put it into big-endian order into the list. I'm not particularly interested in hyper-optimizing in this case; I'd rather the code be clean and readable.
I've got a couple issues that are obvious to me, but the biggest one is that I hate the fact that I am initializing the list with bogus values before I update them. But my choices seem to be that, or adding the elements in ascending order, which seems to make the code to extract the bytes significantly more complex.
Am I missing a better solution?
public void Add32BitValue(int value) {
// Adding 4 elements first to the list, so that
// I can modify them so they'll be in big endian
// order.
// (The code to directly add them in big endian
// order seems much more complex.)
for (int i=0; i<4; i++) {
list.add((byte)0);
}
// Now that the elements are in the arraylist, they
// can be set.
for (int i = 3; i >= 0; i--) {
list.set(list.size() + i - 4, (byte)value);
value = value >> 8;
}
}