java方法不能返回多个值的原因是什么?

Jad*_*ine -1 python java

正如您在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有没有限制,所以方法不能返回多个值?

Dan*_*man 10

严格来说,Python也不会返回多个值.1, 2, 3是一个元组; 只是Python的语法支持自动将该元组解压缩为单独的变量.


Tig*_*kT3 8

Python函数只返回一个值.

>>> def myfun():
...     return 1, 2, 3
...
>>> a = myfun()
>>> type(a)
<class 'tuple'>
Run Code Online (Sandbox Code Playgroud)

如您所见,它是一个容器,就像您在Java中所需要的那样.