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}

4 Upvotes

19 comments sorted by

View all comments

3

u/hibbelig 21h ago

It's not that current.next and current.getNext() return different values. It is more that .getNext() can execute additional logic:

It could run consistency checks: perhaps you aren't allowed to call .getNext() before you have called .initialize() -- then the latter can set a boolean and the former can check it.

It could cache values so that .getNext() becomes faster.

It could compute a value that isn't actually present as the value of a member variable.

So there is guidance to make current.next a private field and current.getNext() a public method: this prevents "others" from accessing current.next directly, and thus ensures that the additional logic in getNext actually runs.

Maybe many methods such as getNext just say return next; and nothing else, but if some of them execute additional logic, then the caller doesn't need to know about it. You can add logic later, and the calling code doesn't need to change.

1

u/gerladokennedy 21h ago

okay thank you very much for your great response