# Breaking a 32-bit value into bytes for an ArrayList

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++) {
}

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

• What's the context? Why do you want bytes in a list? How many of these integers and lists are you going to have? Jan 15 '19 at 21:41
• One list. Not sure about the exact size range, but I'm looking at maybe 100K bytes. I'm implementing something similar to a stack (but would like to be able to look at a bunch of stuff by index rather than popping/peeking groups of 20-100 values). I'm not wholly convinced that this is the right approach/collection...but that's okay. I'm doing this as a project to become familiar with Java vs my normal environment. Jan 15 '19 at 22:03
• I was thinking about using Stack initially (since my project is an interpreter, and this is the stack)...but since different objects that are of different sizes and purposes can go on the stack and need to have their bytes readable, it didn't seem like a great fit...though, thinking about it I guess I could create some kind of parent class that goes into the stack...but that's also weird to me, because the objects wouldn't really have much in common (other than that they can both go on the stack.) Jan 15 '19 at 22:05

Assuming your list was defined elsewhere, you could append the bytes of value as follows.

for(int i = 3; i >= 0; i--) {