从一个方法返回两个变量
问题描述:
如何正确编写以下代码?
How to write the following code correctly?
public String toString(int[] position, int xOffset, int yOffset) {
String postn = String.format("[%d,%d]", position[0], position[1]);
String movm = String.format("[%d,%d]", xOffset, yOffset);
return (postn, movm);
}
出现以下错误
movm cannot be returned.
答
使用 Java 8 时你可以使用配对课程。
When using Java 8 you could make use of the Pair class.
private static Pair<String, String> foo (/* some params */) {
final String val1 = ""; // some calculation
final String val2 = ""; // some other calculation
return new Pair<>(val1, val2);
}
否则只返回一个数组。