How to return multiple objects from a Java method?

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

    Can do some thing like a tuple in dynamic language (Python)

    public class Tuple {
    private Object[] multiReturns;
    
    private Tuple(Object... multiReturns) {
        this.multiReturns = multiReturns;
    }
    
    public static Tuple _t(Object... multiReturns){
        return new Tuple(multiReturns);
    }
    
    public <T> T at(int index, Class<T> someClass) {
        return someClass.cast(multiReturns[index]);
    }
    }
    

    and use like this

    public Tuple returnMultiValues(){
       return Tuple._t(new ArrayList(),new HashMap())
    }
    
    
    Tuple t = returnMultiValues();
    ArrayList list = t.at(0,ArrayList.class);
    
    0 讨论(0)
提交回复
热议问题