How to return multiple objects from a Java method?

前端 未结 25 3128
眼角桃花
眼角桃花 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:42

    In C, you would do it by passing pointers to placeholders for the results as arguments:

    void getShoeAndWaistSizes(int *shoeSize, int *waistSize) {
        *shoeSize = 36;
        *waistSize = 45;
    }
    ...
    int shoeSize, waistSize;
    getShoeAndWaistSize(&shoeSize, &waistSize);
    int i = shoeSize + waistSize;
    

    Let's try something similar, in Java.

    void getShoeAndWaistSizes(List shoeSize, List waistSize) {
        shoeSize.add(36);
        waistSize.add(45);
    }
    ...
    List shoeSize = new List<>();
    List waistSize = new List<>();
    getShoeAndWaistSizes(shoeSize, waistSize);
    int i = shoeSize.get(0) + waistSize.get(0);
    

提交回复
热议问题