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/tsvk 22h ago

When you refer to current.next, you are accessing directly a member field variable called next of the object reference called current. The visibility of the field next is set to such a level in the object current that you are able to access the field from outside the object, in other words the field is not private. It's basically a member field variable that is accessed directly from outside the object.

Usually this is not possible, since member field variables are conventionally marked private, which makes access from outside the object is impossible, but in those cases when referring to current.next is possible it means that the field is not set to private but something else, like package private (no visibility modifier) or even public.

On the other hand, when you call current.getNext() you are calling a method called getNext on the current object. The method is free to return whatever it's defined to return, but usually (if standard Java naming conventions are adhered to), it returns the value of the member field of the object called next.

3

u/halfxdeveloper 21h ago

There’s one small distinction that you glossed over. It it has major implications. The getNext() is a function which means that not only can it return any value, such as a computed value, but it can do anything such as call other methods, create log entries, etc. Students are often just told it’s for accessing private variables but it’s so much more.

2

u/Spare-Plum 20h ago

Larger distinction you glossed over - an element in a custom linked list can implement the Iterator interface, which would allow plug and play iteration with a whole host of compatible code

Only caveat is that Iterator's function is just "next()", while the method stated is "getNext()".

IMO if this is a custom class it's best to change "getNext()" to "next()" and make it into an iterator so it can work with for loops and many other libraries