0

I'm relatively new to coding so I apologize if this question is stupid. Why is the Arraylist numbers getting affected by what is happening within the function changeParam with the parameter of Arraylist for example...

public class Test {
static ArrayList<Integer> numbers = new ArrayList<>();
 public static void main(String[] args) {
     for(int i = 0; i <= 100; i++){
         numbers.add(i);
        }
     changeParam(numbers);
     System.out.println(numbers);
    }
 public static void changeParam(ArrayList<Integer> A){
A.clear();
}
}

Why when numbers is printed does it come out empty?

braX
  • 11,506
  • 5
  • 20
  • 33
  • You are passing the `numbers` list as an argument to `changeParam`, which clears the list. `A` and `numbers` refers to the same list when you pass `numbers` to the function. – marstran Mar 14 '20 at 22:20
  • 1
    Why do you believe `A` is a different list than `numbers`? Do you believe it copied the entire list on the method call? Perhaps because you were told Java is pass-by-value? If so, then be aware that it is the *reference* to the list that is passed by value, not the `ArrayList` *object*. – Andreas Mar 14 '20 at 22:23
  • This is because your references : ``numbers`` and ``A`` points on the same object address and values of members variables are copied, from ``numbers`` variable to ``A`` parameter. You can test it my calling the function ``System.identityHashCode(Object object)`` on ``numbers`` and ``A``. You will see that they have the same address. This lecture could help you understand more : https://www.journaldev.com/3884/java-is-pass-by-value-and-not-pass-by-reference – Harry Coder Mar 14 '20 at 22:40

0 Answers0