简体   繁体   中英

How does reference work in Java?

I know objects are passed by value, but the value of the reference.

So say I have a class:

  //Definition for singly-linked list.
  public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
  }

I do something like:

ListNode n = new ListNode(3);
ListNode n1 = new ListNode(4);
n.next = n1;

So now I have a linked list:

n -> n1 -> null

Suppose now I do something like:

/* Previous code from above
ListNode n = new ListNode(3);
ListNode n1 = new ListNode(4);
n.next = n1; */

ListNode ref = n;
n = n.next;

What does ref point to now?

Your Linked List initially is as below

n -> n1 -> null , if represented by values its like 3 -> 4 -> null .

When you do ListNode ref = n; then ref refers to node with value 3.

Now when you do n = n.next; reference variable n refers to node with value 4. Reference variable ref is unaffected by this assignement. ref still refers to the node with value 3.

If n = n.next was not done and instead after doing ListNode ref = n; the value was modified like n.val = 100 then as ref and n both would have been refering to same object ref.val == 100 would have been true .

PS

There is difference between reference and Objects. Reference variables refers to the Objects. When two references refers same objects, then if modifications* (usually using . dot operator) in the state of object is done by one reference, same will be reflected ifthe object state is read by other reference referring to same object. But if one of the the reference is made to refer to another object (using assignment operator = ), it does not affect other reference, it still refers to the object it was referring to.

*Note not always state is modified by operations Like .trim() on String object as String class is immutable. Just remember debugging and java docs are your greatest helping tools. When ever in doubt try it yourself,debug the code you write, refer the java docs and you will have a smooth learning. Happy Learning, cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM