I stumbled upon a very puzzling feature(?) of Java.
It seems that using a "new" keyword to replace a method argument kind of shifts that object into a different scope:
import java.util.ArrayList;
public class Puzzle {
public static void main(String[] args) {
ArrayList outer = new ArrayList();
outer.add(17);
Puzzle.change(outer);
outer.add(6);
System.out.println(outer);
// excpected output:
// [23]
// [23, 6]
//
// actual output:
// [23]
// [17, 7, 6]
}
public static void change(ArrayList inner) {
inner.add(7);
inner = new ArrayList();
inner.add(23);
System.out.println(inner);
}
}
Can anyone explain this oddity? I noticed the same kind of behavior with assignment. That's not a puzzle but a basic concept. Google for "call by value vs call by reference".