How to return multiple objects from a Java method?

前端 未结 25 3123
眼角桃花
眼角桃花 2020-11-21 23:55

I want to return two objects from a Java method and was wondering what could be a good way of doing so?

The possible ways I can think of are: return a HashMap<

25条回答
  •  遥遥无期
    2020-11-22 00:46

    Regarding the issue about multiple return values in general I usually use a small helper class that wraps a single return value and is passed as parameter to the method:

    public class ReturnParameter {
        private T value;
    
        public ReturnParameter() { this.value = null; }
        public ReturnParameter(T initialValue) { this.value = initialValue; }
    
        public void set(T value) { this.value = value; }
        public T get() { return this.value; }
    }
    

    (for primitive datatypes I use minor variations to directly store the value)

    A method that wants to return multiple values would then be declared as follows:

    public void methodThatReturnsTwoValues(ReturnParameter nameForFirstValueToReturn, ReturnParameter nameForSecondValueToReturn) {
        //...
        nameForFirstValueToReturn.set("...");
        nameForSecondValueToReturn.set("...");
        //...
    }
    

    Maybe the major drawback is that the caller has to prepare the return objects in advance in case he wants to use them (and the method should check for null pointers)

    ReturnParameter nameForFirstValue = new ReturnParameter();
    ReturnParameter nameForSecondValue = new ReturnParameter();
    methodThatReturnsTwoValues(nameForFirstValue, nameForSecondValue);
    

    Advantages (in comparison to other solutions proposed):

    • You do not have to create a special class declaration for individual methods and its return types
    • The parameters get a name and therefore are easier to differentiate when looking at the method signature
    • Type safety for each parameter

提交回复
热议问题