不要返回包含两个值的数组或使用泛型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());}


