r/javahelp • u/gerladokennedy • 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
u/hibbelig 21h ago
It's not that
current.nextandcurrent.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.nexta private field andcurrent.getNext()a public method: this prevents "others" from accessingcurrent.nextdirectly, and thus ensures that the additional logic ingetNextactually runs.Maybe many methods such as
getNextjust sayreturn 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.