I have a problem trying to understand the code of a basic nodelist. The nodes (class ListNode) contain three variables; A String “key”, a Value “value” and then another node “next”. So far so good. However, in the class with the aptly name ListMap, we have the put() method which I have a hard time making sense of:
public void put(String key, int value) {
ListNode l = search(key, head);
if ( l==null ) {
head = new ListNode(key, value, head);
} else {
l.value = value;
}
protected static ListNode search(String key, ListNode l) {
if (l==null) {
return null;
} else if (key.equals(l.key)) {
return l;
} else {
return search(key, l.next);
}
}
The method searches for the String “key”, and if there is one in the list, it replaces its value with the new value given as the second parameter.
What I can’t get my head around is this variable l, which is being assigned the node which shares the same “key” or String as the first parameter.
When l.value is set to value, why does this affect the list?
Isn’t the variable l just a copy of one of the nodes in the list, not not the actual node?
I apologize in advance for such a confusing question, but I hope one of you can make sense of it.
No, it’s a reference to a node (like pointer in C language). You can have several references to the same object and changes made to that object via one reference are of course visible when the same object is accessed via different reference. It’s like aliases.
Here is a simplified example: