While searching whether this was already answered, I found Are class members guaranteed to be contiguous in memory?, but that deals with C++, not Java.
To provide context, I have a background in Go and I'm learning Java. I know that with Go, I can write a struct using pointers like this:
type myStruct struct {
firstMember *string
secondMember *int
}
But when studying Go in detail, I often read about this being a bad idea unless you really need them to be pointers, because it means the values for each member can be spread anywhere across dynamic memory, hurting performance because it's less able to take advantage of spatial locality in the CPU.
Instead, it's often recommended to write the struct this way, without using pointers:
type myStruct struct {
firstMember string
secondMember int
}
As I learn how to effectively write Java, I'm curious if I have this same tool in my toolset when working with Java. Since I don't have the ability to use pointers (because every variable whose type is a class is a reference to that class, effectively a pointer), I can only write the class using String
and int
:
class MyClass {
String firstMember;
int secondMember;
}
Realizing that this was the only way to write a class for my data structure led me to the question posed.