简体   繁体   English

多个Java引用是否会使使用的内存增加一倍?

[英]Do multiple Java references double the memory used?

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. 最近,我学习了如何在Java中创建对同一可变对象的多个引用,该引用在创建的复合列表中使用。 My question is, am I doubling my memory usage, or just using an additional int as a memory address? 我的问题是,我是将内存使用量增加一倍,还是仅使用一个附加的int作为内存地址? 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; 因此,在这种情况下,我认为内存中发生的事情是我有2个引用是32位内存地址,而一个对象包含我的64位长。 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. 我问是因为我想使用更大的对象,这将允许我将它们包含在多个列表中,同时适当地减少内存使用量。

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 该对象比64位占用更多空间,因为这只是为其字段分配的内存

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; 因此,在这种情况下,我认为内存中发生的事情是我有2个引用是32位内存地址,而一个对象包含我的64位长。 is this accurate? 这个准确吗?

You have one object and two references a and b to refer that object. 您有一个对象,两个引用ab引用了该对象。 That object has a long data . 该对象的data很长。

You can alter/query the state of that object by using both references a and b . 您可以同时使用引用ab来更改/查询该对象的状态。

You are right. 你是对的。 However, if your code is running on a 64 bits architecture, references are 64 bits instead of 32 bits. 但是,如果您的代码在64位体系结构上运行,则引用是64位而不是32位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM