从Java中的函数返回多个值

如何从Java中的函数返回多个值? 任何人都可以使用元组提供示例代码吗? 我无法理解元组的概念。


public class Tuple{ public static void main(String []args){ System.out.println(f()); } static Pair f(){ return new Pair("hi",3); } public class Pair { public final String a; public final Integer b; public Pair(String a, Integer b) { this.a = a; this.b = b; } } } 

上面的代码有什么错误?

创建一个包含所需多个值的类。 在您的方法中,返回一个对象,该对象是该类的实例。 瞧!

这样,您仍然可以返回一个对象。 在Java中,无论可能是什么,都不能返回多个对象。

这是你想要的?

 public class Tuple { public static void main(String[] args) { System.out.println(f().a); System.out.println(f().b); } static Pair f() { Tuple t = new Tuple(); return t.new Pair("hi", 3); } public class Pair { public final String a; public final Integer b; public Pair(String a, Integer b) { this.a = a; this.b = b; } } } 

您不能返回多个值。

如果满足您的目的,您可以返回Array,Collection。

注意:它将是一个值,对您的Object [of array,collection]的引用将返回。

您可以从java函数返回一个数组:

  public static int[] ret() { int[] foo = {1,2,3,4}; return foo; } 

你不能在java中返回多个值(这不是python)。 编写一个只返回数组或列表或任何其他对象的方法

如果您返回的内容与您的情况类似,则会有不同的数据类型。 或者,例如,让我们说你要返回一个String名称和一个整数年龄。 你可以从org.json库中获得JSON。 您可以访问http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm获取jar

 public JSONObject info(){ String name = "Emil"; int age = 25; String jsonString ="{\"name\":\""+ name+"\",\"age\":"+ age +"}"; JSONObject json = new JSONObject(jsonString); return json ; } 

之后,如果您想在程序中的某个位置获取数据,那么您就是这样做的:

 //objectInstanceName is the name of the instantiated class JSONObject jso = objectInstanceName.info(); String name = jso.getString("name"); int age = jso.getInt("age"); System.out.println(name + " is "+ age + " years old"); //Output will be like Emil is 25 years old 

希望你试试看。 或者如果你没有,你可以在java中阅读更多有关JSON的内容。