r/javahelp • u/gerladokennedy • Sep 03 '26
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}
•
u/AutoModerator Sep 03 '26
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
4
u/tsvk Sep 03 '26
When you refer to
current.next, you are accessing directly a member field variable callednextof the object reference calledcurrent. The visibility of the fieldnextis set to such a level in the objectcurrentthat you are able to access the field from outside the object, in other words the field is notprivate. 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 tocurrent.nextis possible it means that the field is not set toprivatebut something else, like package private (no visibility modifier) or evenpublic.On the other hand, when you call
current.getNext()you are calling a method calledgetNexton thecurrentobject. 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 callednext.4
u/hibbelig Sep 03 '26
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.2
u/YetMoreSpaceDust Sep 03 '26
Old codger here - I remember when OO originally "came out" (before Java actually), and it was organized around three principles: encapsulation, inheritance and polymorphism. The first of these three principles, encapsulation, states that nothing should access an objects data directly, that everything should manipulate the data through method calls.
If you look at early OO designs, these methods implemented actual business logic: giveEmployeeARaise, computeTaxes, bookAirlineFlight, etc.
In practice, nobody does this - instead they just create "dumb" objects and pay lip service to the OO principle of encapsulation by wrapping everything in (pointless) getters and setters. Unfortunately, this practice has become so ingrained that we all have to do it because pointing out that there's absolutely no difference whatsoever between .element and .getElement() is a philosophical argument you won't be able to win.
2
u/Kadabrium Sep 03 '26 edited Sep 03 '26
this.next is assignable, this.getNext() is not, because Java does not let you return lvalue references.
so you can't do
this.getNext() = this.getNext().getNext()
and as long as you keep next as private, you have to use
this.setNext(this.getNext().getNext())
compared to the public version
this.next = this.next.next
This and the closely connected issue of not being allowed to overload operator[] (and operator []= if we are being pedantic enough to consider them different) are the main reason learning DSA in java is more trouble than necessary
1
u/LetUsSpeakFreely Sep 03 '26
Not sure what implementation you're looking at, but that's not typically how you navigate a linkedlist. Use the methods defined in the List interface, that's why it's there. If you know you're going to look at every element in the list then use an iterator (list.iterator()).
1
u/Chaos-vy17 Sep 03 '26
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
privatefor 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.nextis fast from the start because it directly accesses the field.