I'm using java8, SpringBoot 2, and JPA2 and I'm run in a strange problem. Suppose the following code:
public void doSome() {
List<Integer> arr = new ArrayList<>(Arrays.asList(1,2,3,4,5));
List<Integer> arr2 = new ArrayList<>(Arrays.asList(1,2,3,4));
otherMethod(arr, arr2);
System.out.println(arr);
}
In the same class I have the otherMethod() and with this version:
public void otherMethod(List<Integer> arr, List<Integer> arr2) {
arr = arr.stream().filter(x -> !arr2.contains(x)).collect(Collectors.toList());
System.out.println(arr); // here print just 5
}
When code flow bring me back to doSome():
System.out.println(arr); // print [1,2,3,4,5]
If I change my otherMethod() as follows:
public void otherMethod(List<Integer> arr, List<Integer> arr2) {
// arr = arr.stream().filter(x -> !arr2.contains(x)).collect(Collectors.toList());
arr.removeIf(x -> x < 3);
System.out.println(arr); // print [3,4,5]
}
and the changes affect the Object I have passed by reference, in doSome() method I see:
System.out.println(arr); // print [3,4,5]
I don't understand why with arr.stream().filter(x -> !arr2.contains(x)).collect(Collectors.toList()) changes doesn't affect my Object passed by reference.
where am I wrong?