java - Java中如何获取类的对象的引用值?

标签 java memory memory-management

public class Box {

    int height;
    int length;
    int width;

}



public class Volume {

    public static void main(String args[]){

        Box mybox = new Box();
        Box mybox1= mybox;
        Box mybox2 = new Box();


        System.out.println(" The address of the mybox object is:"+System.identityHashCode(mybox));
        System.out.println(" The value of the mybox object is:"+mybox);

        System.out.println(" The address of the object mybox1 is :"+ System.identityHashCode(mybox1));
        System.out.println(" The value of the mybox1 object is:"+mybox1);


        System.out.println(" The address of the object mybox2 is :"+ System.identityHashCode(mybox2));
        System.out.println(" The value of the mybox2 object is:"+mybox2);

    }
}

这个程序的目标是帮助我理解 Java 中对象创建和内存分配的概念。根据我的理解,new运算符应该为对象创建一个内存并返回存储在内存中的引用。为了获取对象的地址,我使用 System.identityHashCode 函数。为了获取存储在该内存地址中的引用的值,我直接打印该对象。下面我们可以看到结果。

 The address of the mybox object is:1956725890

 The value of the mybox object is:Box@74a14482

 The address of the object mybox1 is :1956725890

 The value of the mybox1 object is:Box@74a14482

 The address of the object mybox2 is :356573597

 The value of the mybox2 object is:Box@1540e19d

根据上述结果,我的理解是 mybox 和 mybox1 将具有相同的地址,并且它们将在该地址中携带相同的引用值,因为 mybox1 未实例化并被分配给 mybox。 mybox2 将有一个新地址,并且该地址中将有一个新的引用值。

所以我的问题是

  • 如果没有实例化,mybox1 如何拥有地址以及该地址中的引用?

  • Java完整引用这本书确实提到,每个对象实例化后都会保存实际对象Box的内存地址。那么为什么mybox2中存储的引用值与存储的引用值不同呢在我的盒子里?我假设只需打印变量,它就会给我存储在该变量中的值,这是对对象 Box 的引用。

感谢大家提供的任何建议,可以帮助我理解 java 的基本概念。我是一名新手,我非常感谢 stackoverflow 成员传播的丰富知识。

最佳答案

a) 线路Box mybox1= mybox;使变量 mybox1指向 mybox 创建的对象多变的。因此,两个变量 myboxmybox1指向同一个对象。请注意new运算符在前两行中仅使用一次。

b) 由于您正在为 mybox2 创建一个新对象在线Box mybox2 = new Box(); ,它将在堆中创建一个全新的对象。变量的值myboxmybox2您看到的基本上是类的名称,后跟十六进制格式的对象的哈希码。

当您打印变量 mybox 时使用System.out.println()它在内部执行 toString 方法:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

关于java - Java中如何获取类的对象的引用值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34610573/

相关文章:

java - EasyMock:部分模拟类

java - Jackson JSON 处理键名称 = ognl 名称

xcode - AVAudioPlayer 内存泄漏

haskell - Cabal 安装标准内存不足

javascript - 如何在 Node.js 中存储 100GB 的内存

garbage-collection - 我可以在性能监视器中使用哪个计数器来查看有多少内存正在等待 GC?

javascript - 原始数据方法

java - 我们是否需要显式关闭在方法参数中作为匿名类传递的 Streams 或 Reader?

java - 测java短时间运行线程执行时间

Linux 内存使用量远大于所有应用程序使用内存的总和?