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
  • 1,919
  • 2
  • 20
  • 46
Shemesh
  • 29
  • 7

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,731
  • 18
  • 26
Avinash
  • 3,744
  • 2
  • 19
  • 40