我试图从一个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);
}
错误:
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结果:1
与其返回包含这两个值的数组或使用通用的Pair类,不如考虑创建一个表示希望返回的结果的类,并返回该类的一个实例。给类一个有意义的名字。与使用数组相比,这种方法的好处是类型安全,它将使您的程序更容易理解。
注意:泛型的Pair类,正如这里其他一些回答中提出的那样,也提供了类型安全,但不传达结果所代表的内容。
示例(没有使用真正有意义的名称):
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());
}
您不需要创建自己的类来返回两个不同的值。就像这样使用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);
}
甚至还有类型安全的好处。