Why there is no way to pass by reference in java

后端 未结 3 576
滥情空心
滥情空心 2021-01-29 13:56

I guess java does not have the option \"pass by reference\" .But why ? Because sometimes it is very needed.

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 14:21

    I guess the only place you really need pass by reference is to return multiple values from a function like the out keyword in C. To do this in Java, you can either create a class to hold the objects or use an existing Pair class offered by many libraries.

    Similarly, you can pass a stub object that refers to something else and then you can change the reference in the object and see it reflected externally:

    public static class Holder {
        public T value;
    
        public Holder(T value) {
            this.value = value;
        }
    }
    
    private Holder itsValueCanBeSeenAsPassedByReferencce
    = new Holder("a");
    
    public void doSomething(Holder holder) {
        holder.value = "b";
    }
    
        

    提交回复
    热议问题