r/javahelp 22h ago

linked lists

-- solved thank you all

what is the difference between accessing the next node using a get method or without, as in: "current.next" vs "current.getNext()" and the same applies for accessing an element, whats the difference between use the get or not, as in: "current.element" vs "current.getElement()" where current is just the name for the node variable. ive looked at so many different explanations but i cant seem to grasp the idea
edit: this is from a data structures pov, im implementing methods for the singly and doubly linked list classes in java
i want to know if they return different things or if using .next or .getnext makes a difference in the outcome, is there a scenario i should be using strictly .next or .getnext, and the getter method has no further conditions its just {return next}

3 Upvotes

19 comments sorted by

View all comments

1

u/Chaos-vy17 21h ago

When devs do curr.next, you are accessing the member field variable directly.

When devs do curr.getNext(), it goes something like this to the JVM:

Devs want the next element → it calls invokevirtual → then the value is returned/passed.

Here, I am only showing two operations, but there may be more steps involved.

Why do users use getNext()?
Devs generally keep fields private for encapsulation and expose methods for accessing and mutating them through a getter and setter:

So, is getNext() slow?

Obviously, initially, yes. But not for long. Once the operation becomes hot enough and crosses the C1/C2 JIT optimization thresholds, the JVM can inline the getter, and both can become essentially the same at the machine-code level.

However, curr.next is fast from the start because it directly accesses the field.

1

u/gerladokennedy 21h ago

okay thank you
is there a difference in the value returned from .next and .getnext? does it make a difference in the outcome

2

u/Chaos-vy17 21h ago

Same field + same getter definition = same returned value and therefore the same outcome.

1

u/gerladokennedy 21h ago

okay thank you so much for your help