Java method argument puzzle

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".

以上就是Java method argument puzzle的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准