0

I wrote a code for changing values of list by function:

package test3;
import unit4.collectionsLib.*;
public class main {

    public static void change (Node<Integer>first) {
        first = new Node<Integer>(12,first);
    }
    public static void main(String[] args) {
        Node<Integer> first = new Node<Integer>(1);
        first = new Node<Integer>(2,first);
        first = new Node<Integer>(3,first);
        Node<Integer> pos = first;
        while (pos!=null) {
            System.out.print(pos.getInfo()+"->");
            pos = pos.getNext();
        }
        System.out.println();
        change(first);
        pos = first;
        while (pos!=null) {
            System.out.print(pos.getInfo()+"->");
            pos = pos.getNext();
        }               
    }        
}

the output is :

  3->2->1->
3->2->1->

How do I pass an object in the function for changing the list?

Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
Shemesh
  • 39
  • 11

1 Answers1

0

Java is always pass by value but you can do something like this.

public class main {

    public static Node<Integer> change(Node<Integer> first)
    {
        return new Node<Integer>(12,first);
    }
    public static void main(String[] args) {
        Node<Integer> first = new Node<Integer>(1);
        first = new Node<Integer>(2,first);
        first = new Node<Integer>(3,first);
        Node <Integer>pos = first;
        while (pos!=null){
            System.out.print(pos.getInfo()+"->");
            pos = pos.getNext();
        }
        System.out.println();
        pos = change(first);
        while (pos!=null){
            System.out.print(pos.getInfo()+"->");
            pos = pos.getNext();
        }

    }

}
Ward
  • 2,799
  • 20
  • 26
Avinash
  • 4,115
  • 2
  • 22
  • 41