I decided to write the simplest method - empty the node.

public static void Node <Integer> n1 (Node <Integer> n1) { while (n1 != null) n1 = n1.getNext(); } 

Found that the node has not changed. Moved the cycle to the main method - it works.

The question is: why the node has not changed inside the method, is the node an object? Why do stacks, queues, arrays, and other objects change inside the void methods, but the node does not?

UPD: this method which changes adds to the node the chain at the end of the node works.

 public static void what (Node <Integer> n1, int a) { while (n1.hasNext()) n1 = n1.getNext(); Node <Integer> n7 = new Node <Integer> (a); n1.setNext(n7); } 
  • @diraria updated the question and read these topics. I still do not understand why the first method does not change the node and the second regularly performs its task. - Alex Shvachko
  • Within the method, you can change the fields of the object passed by reference as an argument. However, if you change the object link itself, there will be no result. Simply return the updated link from the method if you wish. - Alex Chermenin
  • @AlexChermenin what? I do not really understand what you are saying. Object link? I thought that in Java there are no pointers o_0 - Alex Shvachko
  • @AlexShvachko may not quite correctly put it - yes, all parameters in Java are passed by value, but such a value for the reference type is the object reference in memory. - Alex Chermenin

1 answer 1

You do not fully understand how it works. A reference to the object is passed to the method, let it be a link that looks at the object n1 : A -> n1

When you perform an assignment operation in your method, n1 = n1.getNext(); your link will look at the next Node , A -> n1.getNext() , while Node n1 itself will not change, and you want to change it.
Here is an example:

 public void example(){ List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3)); wrongChangeList(list); System.out.println(list); correctChangeList(list); System.out.println(list); } private void correctChangeList(List<Integer> list){ list.clear(); list.addAll(Arrays.asList(10, 20, 30)); } private void wrongChangeList(List<Integer> list){ list = Arrays.asList(10, 20, 30); } 

[1, 2, 3]

[10, 20, 30]

When you call wrongChangeList your external list will not change, only the link inside the wrongChangeList method will wrongChangeList In the second case, we change the object itself.

I hope you can understand on the basis of this how your second method works and why the first one does not work.

  • I got it. Thank you for your help. - Alex Shvachko