Java Object Variable Size of another Object?

If I have an object:


public class Element {
	public int id; // 4 byte
	
	public Element(int id) {
		this.id = id;
	}
}
// This would be a total of 12 bytes from my understanding (8 for header, 4 for int id)

// and then have another class
public class Unit {
	public int uid; // 4 byte
	public Element element; // ?? byte
}

would the the second object’s size be: 16 bytes?
8 header, 4 int uid, 4 Element (reference?)
or would it contain the size of the Element object as well thus end up being 24 bytes total?
8 header, 4 int uid, 12 Element
What I’m asking is how many bytes is ?? byte within the Unit object?

I’ll end up using a lot of objects so I need to figure out the best way to store an object.
Would it be better to store variable element within Unit as an int elementId field or use Element element? With int I’d be doing a search to grab the element but I will be storing all of these into a HashMap so it wouldn’t be a linear search.

How it’ll work is both are stored in 2 separate HashMap, but when I need to read the Element of Unit, I can use just unit.element to return Element or do elementHashMap.get(unit.elementId) depending on how I structure the data

The size of element in your second class will be 4 bytes (the cost of the reference or pointer…however you want to look at it.)

It can just as well be 8 bytes per reference, on a 64 bit JVM where pointers are not compressed.

The sizeof an instance of a class is also rounded up to a multiple of 16 bytes.

Which brings up a question I’ve never bothered to figure out: Is pointer compression the default?

Uncompressed OOPs is the default I think according to this.

Cas :slight_smile:

So your Unit object will be 8 + 4 + 8 = 20 bytes.