I defined static final ArrayList and then I've send it to other class to be changed. But it should change only locally in the second class due to he is final, like the int in my example. Why is it changed in the Main class also?
Small code example:
public class Main {
private static final ArrayList<String> myList = new ArrayList<>(Arrays.asList("One", "Two"));
private static final int num = 5;
public static void main(String[] args) {
SecondClass second = new SecondClass(myList,num);
System.out.println("List in Main: "+myList.get(0));
System.out.println("Num in Main: "+num);
}
}
public class SecondClass {
public SecondClass(ArrayList<String> list, int num)
{
list.set(0,"Three");
num = 10;
System.out.println("List in second: "+list.get(0));
System.out.println("Num in Second: "+num);
}
}
My output:
List in second: Three
Num in Second: 10
List in Main: Three
Num in Main: 5
What I expected it to be:
List in second: Three
Num in Second: 10
List in Main: One
Num in Main: 5