How to return more than one value from a function in Java? Can anyone give sample code for doing this using tuples? I am not able to 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 mistake in the above code?
If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function.
We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.
In order to return multiple values in Java, we can use an array to stores multiple values of the same type. However, we can use this approach only if all the values to be returned are of the same type. This is the simplest approach to return both primitive type data as well as reference data types.
Create a class that holds multiple values you need. In your method, return an object that's an instance of that class. Voila!
This way, you still return one object. In Java, you cannot return more than one object, whatever that may be.
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;
}
}
}
You can't return more than one value.
You can return Array,Collection if it satisfies your purpose.
Note: It would be one value, reference to your Object[of array,collection] would be return.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With