正如您在python中所知,函数可以返回多个值
例如:
def myfun():
return 1, 2, 3
Run Code Online (Sandbox Code Playgroud)
我们可以这样称呼它:
a, b, c= myfun()
Run Code Online (Sandbox Code Playgroud)
但是在JAVA中,我们不能返回更多的那个值,所以我们必须创建一个包含我们想要返回的值的对象:
class MyObject {
private Integer a;
private Integer b;
private Integer c;
public Integer getA() {
return a;
}
public void setA(Integer a) {
this.a = a;
}
public Integer getB() {
return b;
}
public void setB(Integer b) {
this.b = b;
}
public Integer getC() {
return c;
}
public void setC(Integer c) {
this.c = c;
}
}
Run Code Online (Sandbox Code Playgroud)
我们的函数将返回此对象
例如:
public MyObject myfun(){
MyObject myObject = new MyObject();
myObject.setA(1);
myObject.setB(2);
myObject.setC(3);
return myObject;
}
Run Code Online (Sandbox Code Playgroud)
我们用这种方式称呼它:
obj = myfun();
Integer a = obj.getA();
Integer b = obj.getB();
Integer c = obj.getC();
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是返回一个包含应返回的所有值的数组
但是这两种方法在编码方面都很难看,JAVA有没有限制,所以方法不能返回多个值?
Python函数只返回一个值.
>>> def myfun():
... return 1, 2, 3
...
>>> a = myfun()
>>> type(a)
<class 'tuple'>
Run Code Online (Sandbox Code Playgroud)
如您所见,它是一个容器,就像您在Java中所需要的那样.