returning multiple values in Java

后端 未结 6 555
时光说笑
时光说笑 2020-12-11 19:14

Preamble: I am aware of using a list or other collections to return a result but then I have to go through the list plucking the results out: see 2nd example

Preambl

6条回答
  •  一个人的身影
    2020-12-11 19:43

    If you need to return multiple values of the same type, then a List or Set is appropriate. It is perfectly valid to return, for example, a variable-length username list as a List. If you know you are always going to return a fixed number of values, I would use an array. For example, in a method that returns a some kind of user ID as three distinct integers, I would use:

    public int[] getUserId(){
        int[] returnArray = new int[3];
        returnArray[0] = getFirstPart();
        returnArray[1] = getSecondPart();
        returnArray[2] = getThirdPart();
    
        return returnArray;
    }
    

    In the caller code, obtaining the values is as simple as array[0], array[1] and array[2]. This is much easier than a Collection, and you will not break anything, because user IDs are defined as being three integers.

    If you really need to return multiple distinct values, then the holder class is the best option, no other way around that. Multiple return values are not supported in Java. But I would rather look at the solution from the design point of view. If a class needs to return multiple distinct values, then it probably does a lot of stuff, some of it unrelated to others. A single piece of code (a class, a method) should always have a single clear purpose and clearly defined responsibilities. Rather that returning multiple distinct values, I would consider splitting the method into multiple shorter method or define an inteface to externalise all the functionality. If those return values are related in any way and wouldn't have meaning if taken apart, then I think they deserve a class on their own.

提交回复
热议问题