简体   繁体   English

Java如何为构造函数中声明的对象和变量命名的对象分配不同的内存?

[英]How does Java allocate memory differently for an object declared in a constructor and an object named by a variable?

Using Java IO streams, it is quite often we use objects solely as constructors for other objects. 使用Java IO流,通常我们仅将对象用作其他对象的构造函数。 I am interested in the memory implications of this prospect. 我对这种前景的记忆含义很感兴趣。 For example, how does memory allocation differ in these two statements that do the same thing? 例如,在执行相同操作的这两个语句中,内存分配有何不同?

FileInputStream inputFile = new FileInputStream("filepath");
Scanner inStream = new Scanner(inputFile);

and

Scanner inStream = new Scanner(new FileInputStream("filepath"));

The first one will allocate a named variable in the current stack frame. 第一个将在当前堆栈帧中分配一个命名变量。 On the heap, there is no difference - or there shouldn't be but the VM is of course free to optimize the code in some way as long as the rules are obeyed. 在堆上,没有区别-或应该没有区别,但是VM只要遵循规则,就可以自由地以某种方式优化代码。

没有区别。两者都是一样的。

在第一个示例中,JVM保留对FileInputStream的引用,而在第二个示例中,JVM创建一个未引用的对象,该对象准备在执行该语句后进行垃圾收集。

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

相关问题 (Java)如果声明但未初始化,对象的变量是否使用内存空间? - (Java) Does a variable of an object use memory space if declared but not initialised? 声明而不初始化对象是否分配内存? - Does stating but not initializing an object allocate memory? Java VM如何分配内存? - How does Java VM allocate memory? Java如何在内存中分配对象的属性? - How does java allocate attributes of objects in memory? 为什么按钮对象的行为取决于声明的位置 - Why does the button object behave differently depending on where it is declared java:类成员的内存如何分配? - java: How does the memory of a class member allocate? 是否可以为Java对象的堆外分配和释​​放内存空间? - Is it possible to allocate and free memory space for a Java Object off-heap? 发生在Java之前的新内存模型是否也适用于声明为volatile的对象的成员? - Does happen-before in Java new memory model also apply to the member of a object which is declared as volatile? 如何将 object 类型作为参数传递给构造函数并将变量转换为它(JAVA)? - How to pass an object type to constructor as argument and cast a variable to it (JAVA)? 如何使用@JacksonXmlProperty反序列化同一对象的不同名称的集合? - How to deserialize differently-named collections of the same object with @JacksonXmlProperty?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM