Return more than one value from a function in Java

后端 未结 6 1366
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 04:31

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.

<
相关标签:
6条回答
  • 2020-12-18 05:12

    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.

    0 讨论(0)
  • 2020-12-18 05:26

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 05:29

    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.

    0 讨论(0)
  • 2020-12-18 05:29

    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 讨论(0)
  • 2020-12-18 05:31

    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

    0 讨论(0)
  • 2020-12-18 05:34

    You can return an array from a java function:

       public static int[] ret() {
          int[] foo = {1,2,3,4};
          return  foo;
       }   
    
    0 讨论(0)
提交回复
热议问题