Question

I have recently learned how to create multiple references to the same mutable object in Java, which I am employing in a compound list of my creation. My question is, am I doubling my memory usage, or just using an additional int as a memory address? Here is the code to which I am specifically referring:

//This is my object containing a 64bit long
public class LongWrapper
{
    long data;
    LongWrapper(int data_in)
    {
        data = data_in;
    }
    public long getData()
    {
        return data;
    }
    public void setData(long data_in)
    {
        data = data_in;
    }
}

//This is my driver program containing references a & b
public class PointerTest 
{
    public static void main(String[] args) 
    {
        LongWrapper a = new LongWrapper(6);
        LongWrapper b = a;
        System.out.println("a = " + a.getData() + " b = " + b.getData());
        a.setData(7);
        System.out.println("a = " + a.getData() + " b = " + b.getData());
    }
}

This is my output:
a = 6 b = 6
a = 7 b = 7

So in this case what I think is happening in memory is that I have 2 references that are 32bit memory addresses, and one object containing my 64bit long; is this accurate?

I ask because I want to use much larger objects and this will allow my to have them in multiple lists whilst properly minimizing my memory usage.

Was it helpful?

Solution 3

So in this case what I think is happening in memory is that I have 2 references that are 32bit memory addresses, and one object containing my 64bit long; is this accurate?

You have one object and two references a and b to refer that object. That object has a long data.

You can alter/query the state of that object by using both references a and b.

OTHER TIPS

You are right. However, if your code is running on a 64 bits architecture, references are 64 bits instead of 32 bits.

You definitely are not doubling your memory usage. you can create as many references as you want pointing to the same object. The references are placed on the stack, and the single object on the heap. The object occupy more space than 64bit because this is only the memory allocated for its field

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top