Returns more than one value from a function in Java

How to return more than one value from a function in Java? Can someone give some sample code for this using tuples? I can not understand the concept of tuples.


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

What is the error in the above code?

+6
java tuples return-type
source share
6 answers

Create a class that contains several values ​​that you need. In your method, return an object that is an instance of this class. Voila!

That way, you still return a single object. In Java, you cannot return more than one object, no matter what.

+4
source share

Is this what you are looking for?

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

You cannot return more than one value.

You can return Array, Collection if it suits your purpose.

Note: This will be a single value, a reference to your object [array, collection] will be returned.

+1
source share

You can return an array from a java function:

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

You cannot return more than one value in java (this is not python). Write a method that simply returns an array or list or any other object like this

+1
source share

What if you return from different data types as your situation. Or, for example, Lets say that you are returning a String name and an integer age. You can JSON from the org.json library. You can get the jar http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

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

Then, if you want to get data somewhere in your program, this is what you do:

 //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 

I hope you try. Or you can learn more about JSON in java if you haven't.

0
source share

All Articles