从Java中的方法返回不同类型的数据? [英] Return different type of data from a method in java?
本文介绍了从Java中的方法返回不同类型的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public static void main(String args[]) {
myMethod(); // i am calling static method from main()
}
.
public static ? myMethod(){ // ? = what should be the return type
return value;// is String
return index;// is int
}
myMethod()
将返回String和int值.因此,从main()
中获取这些返回值,我想出了以下解决方案.
myMethod()
will return String and int value. So take these returning values from main()
i came up with following solution.
创建一个类调用ReturningValues
public class ReturningValues {
private String value;
private int index;
// getters and setters here
}
,然后如下更改myMethod()
.
public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues();
rv.setValue("value");
rv.setIndex(12);
return rv;
}
现在我的问题是,有没有更简单的方法来实现这一目标?
Now my question,is there any easier way to achieve this??
推荐答案
最后,我认为我的方法会更好,因为当返回类型的数量增加时,这种实现会以最佳方式实现.
Finally i thought my way is better since when number of return types go higher this kind of a implementation do that in best way.
public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues();
rv.setValue("value");
rv.setIndex(12);
return rv;
}
这篇关于从Java中的方法返回不同类型的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文