How to return multiple objects from a Java method?

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

    I almost always end up defining n-Tuple classes when I code in Java. For instance:

    public class Tuple2 {
      private T1 f1;
      private T2 f2;
      public Tuple2(T1 f1, T2 f2) {
        this.f1 = f1; this.f2 = f2;
      }
      public T1 getF1() {return f1;}
      public T2 getF2() {return f2;}
    }
    

    I know it's a bit ugly, but it works, and you just have to define your tuple types once. Tuples are something Java really lacks.

    EDIT: David Hanak's example is more elegant, as it avoids defining getters and still keeps the object immutable.

提交回复
热议问题