How to do call by reference in Java?

前端 未结 12 634
悲&欢浪女
悲&欢浪女 2021-01-30 17:36

Since Java doesnt support pointers, How is it possible to call a function by reference in Java like we do in C and C++??

12条回答
  •  时光说笑
    2021-01-30 18:07

    In Java, except for primitives, passing Object to a method/function is always by reference. See Oli Charlesworth's answer for the example.

    For primitive types, you can wrap it using array: For example:

    public void foo(int[] in){
      in[0] = 2;
    }
    
    int[] byRef = new int[1];
    byRef[0] = 1;
    foo(byRef);
    // ==> byRef[0] == 2.
    

提交回复
热议问题