开发者

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.pri开发者_如何学Gontln(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?


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.


You can return an array from a java function:

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


You can't return more than one value in java ( which is not python ). Write a method that just returns array or list or any other object like this


What if what you are returning are of different data types just like your situation. Or for example, Lets say you are returning a String name and an integer age. You can you JSON from the org.json library. You can get the jar at 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 ;
}

Afterwards, if you want to get the 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

Hope you try it. Or you can read more on JSON in java if you HAVEN'T.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜