1

If java is Pass By value Only Than why here its changing the value in list

I tried with Object also

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(12);
    list.add(15);
    list.add(45);
    addExternally(list);

    ListIterator<Integer> 
    iterator = list.listIterator(); 
    while(iterator.hasNext()) {

        System.out.println("Value is : "
                + iterator.next()); 
    }
}

private static void addExternally(List<Integer> list) {
     list.add(11);
     list.add(12);

}

it should not take the changes from addExternally method but its taking why

pradeep
  • 11
  • 3
  • 1
    The value that is being passed is the value of the reference to the list. Reassigning `list` inside the method won't be visible on the outside but changing the list itself (i.e. the elements in the list) will be. – Thomas Jun 19 '19 at 10:27

1 Answers1

2

This is because the reference passed to the method actually refers to the same object as the one referred in your main method.

For more : https://stackoverflow.com/a/4893009/6671004

If you want to make temporary changes to your list, you can use :

List<Integer> tempList = new ArrayList<Object>(list);

or use

List<Integer> tempList = (ArrayList<Integer>) list.clone();
Shrey Garg
  • 1,317
  • 1
  • 7
  • 17