简体   繁体   中英

What exactly is the difference between these two statements

I am a beginner in java and i was going through this code

    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?

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

This creates a new ListNode and assigns it to 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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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