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}
2
u/Kadabrium 18h ago edited 18h ago
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
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
0
u/gerladokennedy 21h ago
is there a difference in the actual returned value from using .next or .getnext? if the getter method is just {return next}. this is all from the context of data structures btw like if im creating a method for the single/double linked list class
thank you for your response
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
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 outcome2
u/Chaos-vy17 21h ago
Same field + same getter definition = same returned value and therefore the same outcome.
1
1
u/YetMoreSpaceDust 21h ago
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.
1
0
u/LetUsSpeakFreely 21h ago
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()).
0
u/gerladokennedy 21h ago
im not necessary navigating lists in a normal code this is from a data structures perspective, im creating methods for the singly or doubly linked list classes
1
•
u/AutoModerator 22h ago
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.