如何从 Java 方法返回 2 个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2832472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:23:23  来源:igfitidea点击:

How to return 2 values from a Java method?

javafunctionreturn-value

提问by javaLearner.java

I am trying to return 2 values from a Java method but I get these errors. Here is my code:

我试图从 Java 方法返回 2 个值,但出现这些错误。这是我的代码:

// Method code
public static int something(){
    int number1 = 1;
    int number2 = 2;

    return number1, number2;
}

// Main method code
public static void main(String[] args) {
    something();
    System.out.println(number1 + number2);
}

Error:

错误:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
    at assignment.Main.something(Main.java:86)
    at assignment.Main.main(Main.java:53)

Java Result: 1

Java 结果:1

采纳答案by Jesper

Instead of returning an array that contains the two values or using a generic Pairclass, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

与其返回包含这两个值的数组或使用泛型Pair类,不如考虑创建一个表示要返回的结果的类,并返回该类的实例。给班级起一个有意义的名字。与使用数组相比,这种方法的好处是类型安全,它会使您的程序更容易理解。

Note: A generic Pairclass, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.

注意:Pair这里的其他一些答案中提出的泛型类也为您提供了类型安全性,但不会传达结果所代表的内容。

Example (which doesn't use really meaningful names):

示例(不使用真正有意义的名称):

final class MyResult {
    private final int first;
    private final int second;

    public MyResult(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }
}

// ...

public static MyResult something() {
    int number1 = 1;
    int number2 = 2;

    return new MyResult(number1, number2);
}

public static void main(String[] args) {
    MyResult result = something();
    System.out.println(result.getFirst() + result.getSecond());
}

回答by GuruKulki

you have to use collections to return more then one return values

您必须使用集合返回多个返回值

in your case you write your code as

在您的情况下,您将代码编写为

public static List something(){
        List<Integer> list = new ArrayList<Integer>();
        int number1 = 1;
        int number2 = 2;
        list.add(number1);
        list.add(number2);
        return list;
    }

    // Main class code
    public static void main(String[] args) {
      something();
      List<Integer> numList = something();
    }

回答by Matt

Java does not support multi-value returns. Return an array of values.

Java 不支持多值返回。返回一组值。

// Function code
public static int[] something(){
    int number1 = 1;
    int number2 = 2;
    return new int[] {number1, number2};
}

// Main class code
public static void main(String[] args) {
  int result[] = something();
  System.out.println(result[0] + result[1]);
}

回答by richj

You can only return one value in Java, so the neatest way is like this:

在 Java 中你只能返回一个值,所以最简洁的方法是这样的:

return new Pair<Integer>(number1, number2);

Here's an updated version of your code:

这是您的代码的更新版本:

public class Scratch
{
    // Function code
    public static Pair<Integer> something() {
        int number1 = 1;
        int number2 = 2;
        return new Pair<Integer>(number1, number2);
    }

    // Main class code
    public static void main(String[] args) {
        Pair<Integer> pair = something();
        System.out.println(pair.first() + pair.second());
    }
}

class Pair<T> {
    private final T m_first;
    private final T m_second;

    public Pair(T first, T second) {
        m_first = first;
        m_second = second;
    }

    public T first() {
        return m_first;
    }

    public T second() {
        return m_second;
    }
}

回答by Lars Andren

You could implement a generic Pairif you are sure that you just need to return two values:

Pair如果您确定只需要返回两个值,则可以实现泛型:

public class Pair<U, V> {

 /**
     * The first element of this <code>Pair</code>
     */
    private U first;

    /**
     * The second element of this <code>Pair</code>
     */
    private V second;

    /**
     * Constructs a new <code>Pair</code> with the given values.
     * 
     * @param first  the first element
     * @param second the second element
     */
    public Pair(U first, V second) {

        this.first = first;
        this.second = second;
    }

//getter for first and second

and then have the method return that Pair:

然后让方法返回Pair

public Pair<Object, Object> getSomePair();

回答by Andreas

You also can send in mutable objects as parameters, if you use methods to modify them then they will be modified when you return from the function. It won't work on stuff like Float, since it is immutable.

您也可以将可变对象作为参数发送,如果您使用方法来修改它们,那么当您从函数返回时它们将被修改。它不适用于 Float 之类的东西,因为它是不可变的。

public class HelloWorld{

     public static void main(String []args){
        HelloWorld world = new HelloWorld();

        world.run();
     }



    private class Dog
    {
       private String name;
       public void setName(String s)
       {
           name = s;
       }
       public String getName() { return name;}
       public Dog(String name)
       {
           setName(name);
       }
    }

    public void run()
    {
       Dog newDog = new Dog("John");
       nameThatDog(newDog);
       System.out.println(newDog.getName());
     }


     public void nameThatDog(Dog dog)
     {
         dog.setName("Rutger");
     }
}

The result is: Rutger

结果是:罗格

回答by siva

public class Mulretun
{
    public String name;;
    public String location;
    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]="siva";
        ar[1]="dallas";
        return ar; //returning two values at once
    }
    public static void main(String[] args)
    {
        Mulretun m=new Mulretun();
        String ar[] =m.getExample();
        int i;
        for(i=0;i<ar.length;i++)
        System.out.println("return values are: " + ar[i]);      

    }
}

o/p:
return values are: siva
return values are: dallas

回答by Code ninetyninepointnine

You don't need to create your own class to return two different values. Just use a HashMap like this:

您不需要创建自己的类来返回两个不同的值。只需使用这样的 HashMap:

private HashMap<Toy, GameLevel> getToyAndLevelOfSpatial(Spatial spatial)
{
    Toy toyWithSpatial = firstValue;
    GameLevel levelToyFound = secondValue;

    HashMap<Toy,GameLevel> hm=new HashMap<>();
    hm.put(toyWithSpatial, levelToyFound);
    return hm;
}

private void findStuff()
{
    HashMap<Toy, GameLevel> hm = getToyAndLevelOfSpatial(spatial);
    Toy firstValue = hm.keySet().iterator().next();
    GameLevel secondValue = hm.get(firstValue);
}

You even have the benefit of type safety.

您甚至可以享受类型安全的好处。

回答by Jacob

In my opinion the best is to create a new class which constructor is the function you need, e.g.:

在我看来,最好的方法是创建一个新类,该类的构造函数是您需要的函数,例如:

public class pairReturn{
        //name your parameters:
        public int sth1;
        public double sth2;
        public pairReturn(int param){
            //place the code of your function, e.g.:
            sth1=param*5;
            sth2=param*10;
        }
    }

Then simply use the constructor as you would use the function:

然后像使用函数一样简单地使用构造函数:

pairReturn pR = new pairReturn(15);

and you can use pR.sth1, pR.sth2 as "2 results of the function"

并且您可以使用 pR.sth1、pR.sth2 作为“函数的 2 个结果”

回答by UserF40

Use a Pair/Tuple type object , you don't even need to create one if u depend on Apache commons-lang. Just use the Pairclass.

使用 Pair/Tuple 类型对象,如果你依赖 Apache commons-lang,你甚至不需要创建一个。只需使用Pair类。