简体   繁体   English

这两个语句之间到底有什么区别

[英]What exactly is the difference between these two statements

I am a beginner in java and i was going through this code 我是Java的初学者,正在经历这段代码

    ListNode current = new ListNode();
    current = front;

and

    ListNode current = front;

Arent both set of statements creating a new object or is it that the memory is being reserved only for the first staement andfor the second only a vatriable is getting declared which holds the memory of the fron node? 两组语句都没有创建一个新对象,还是仅为第一个位置保留了内存,而为第二个语句只声明了保存fron节点内存的可变变量?

ListNode current = new ListNode();
current = front;

This creates a new ListNode and assigns it to current . 这将创建一个新的ListNode并将其分配给current It then immediately overwrites that reference, losing the reference to the new object. 然后,它将立即覆盖该引用,从而丢失对新对象的引用。 This is almost certainly a mistake. 这几乎肯定是一个错误。 The code is equivalent to 该代码等效于

new ListNode();
ListNode current = front;

If the ListNode() constructor has no side effects, that first statement is useless, and could just be 如果ListNode()构造函数没有副作用,则该第一条语句是无用的,可能只是

ListNode current = front;

The first statement actually creates a new object (which will be garbage collected soon after because current points to another object in the next instruction), whereas the second one only creates a reference to an existing object. 第一个语句实际上创建了一个新对象(由于current指向下一条指令中的另一个对象,因此将很快被垃圾回收),而第二个语句仅创建对现有对象的引用。

The recommended code is the second one because the ListNode created in the first one is never used so it is useless to instantiate it. 推荐的代码是第二个代码,因为从不使用在第一个代码中创建的ListNode ,因此无法实例化它。

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

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