Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return more than one value from a function in Java

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?

like image 807
tin_tin Avatar asked Jan 21 '11 07:01

tin_tin


People also ask

How can I return multiple values from a function?

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.

Can you return more than 1 value?

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.

How can a function return multiple values from an array in Java?

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.


3 Answers

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.

like image 188
darioo Avatar answered Nov 03 '22 22:11

darioo


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;
        }
    }
}
like image 2
rahul s Avatar answered Nov 03 '22 22:11

rahul s


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.

like image 1
jmj Avatar answered Nov 03 '22 23:11

jmj