Output Parameters in Java

后端 未结 8 877
夕颜
夕颜 2020-12-21 05:36

With a third party API I observed the following.

Instead of using,

public static string getString(){
   return \"Hello World\";
}

i

8条回答
  •  借酒劲吻你
    2020-12-21 06:14

    Something isn't right in your example.

    class Foo {
    
        public static void main(String[] args) {
            String x = "foo";
            getString(x);
            System.out.println(x);
        }
    
        public static void getString(String output){
            output = "Hello World"
        }
    }
    

    In the above program, the string "foo" will be output, not "Hello World".

    Some types are mutable, in which case you can modify an object passed into a function. For immutable types (such as String), you would have to build some sort of wrapper class that you can pass around instead:

    class Holder {
        public Holder(T value) {
            this.value = value;
        }
        public T value;
    }
    

    Then you can instead pass around the holder:

    public static void main(String[] args) {
        String x = "foo";
        Holder h = new Holder(x);
        getString(h);
        System.out.println(h.value);
    }
    
    public static void getString(Holder output){
        output.value = "Hello World"
    }
    

提交回复
热议问题