Understanding Object and Array Implementation

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Understanding Object and Array Implementation

gnb03
Hi,

I want to confirm my understanding of how objects, and arrays are implemented on the stack.
From looking at Figures 11.1 and Figure 11.3 from the book, my basic understanding of objects and arrays is this:

1. An array is a series of consecutive memory addresses in the heap. Each array has a single pointer stored in the stack as a local variable. These pointers points to the first address of each array.

2. An object is an array of arrays. A single object can have multiple, non-adjacent arrays in the heap. These arrays are called fields and they store the instance variables of an object. An object keeps track of its fields/arrays in the heap with a single array in the stack. In this array in the stack, each memory address acts as a pointer for all of the other arrays in the heap.

Can someone tell me if my understanding is correct?

Thanks,

Jason
Reply | Threaded
Open this post in threaded view
|

Re: Understanding Object and Array Implementation

WBahn
Administrator
Your description of arrays is fine, but your description of objects isn't even particularly close.

An object is not an "array of arrays". Like an array, it is a block of memory somewhere on the heap and you access it by means of a pointer whose value is the address of the first word in that block (the block's base address).

So say we have an object that has five words in its block. We need someway of accessing those five words individually, and so we give them names. We associate the field variable 'bob' with the first word, 'sue' with the second word and so on. The compiler is responsible for keeping track of the offset of each declared field variable relative to the beginning of the block and when we reference that variable the offset is added to the block's base address.

We have the exact same issue with an array. If we have an array consisting of five words, we need some way of accessing those words individually. But because an array has the constraint that it must consist of a collection of the same type of variable, we can associate an index value with each word and calculate the address given the index and the base address -- we use the notation myArrayName[index] to give the compiler the needed information.

So an array is simply a special kind of object that allows a simpler and cleaner, but less flexible, means of accessing the individual elements.