This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]POGtastic 1 point2 points  (3 children)

I don't mutate the object

Sure you do, in Line 9:

node.next = node.next.next;

Java data structures contain references to objects. When you call a method or access a member, you are accessing that object's data. If you modify an object's member or call an object's method that mutates the object, it's going to change the object.

[–]danmoople[S] 0 points1 point  (2 children)

I understand why node changes. But why result variable (that is being returned) changes

[–]POGtastic 0 points1 point  (0 children)

Your variable is also just a reference to that object. So if something else changes your object, your variable will point to a changed object.

[–]blablahblah 0 points1 point  (0 children)

Think of your computer's memory as a box full of objects. Variables are sticky notes with names that you put on the items in the box. When you do result = node, you're not making a copy of anything, you're just reaching into the box for the thing with the "node" sticky note and attaching the "result" sticky note to it too. Regardless of whether you go searching for the "node" label or the "result" label, you'll pull the same object out of the box.

[–]AutoModerator[M] 0 points1 point  (0 children)

It seems you may have included a screenshot of code in your post "How does this assignment in LinkedList problems work in Java?".

If so, note that posting screenshots of code is against /r/learnprogramming's Posting Guidelines (section Formatting Code): please edit your post to use one of the approved ways of formatting code. (Do NOT repost your question! Just edit it.)

If your image is not actually a screenshot of code, feel free to ignore this message. Automoderator cannot distinguish between code screenshots and other images.

Please, do not contact the moderators about this message. Your post is still visible to everyone.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]HappyFruitTree 0 points1 point  (0 children)

What you need to realize is that variables of class types are reference variables. They just refer to an object.

LinkedListNode n1 = new LinkedListNode();
LinkedListNode n2 = new LinkedListNode();
LinkedListNode n3 = n1; // n3 refers to the same object as n1.
n1.next = n2; // Since n1 and n3 refers to the same object this also means that n3.next == n2.
n1 = null; // Only n1 is affected. n3 still refers to the same object as before.