How to return multiple values?

Possible duplicate:
How to return multiple objects from a Java method?

Is it possible to return two or more values ​​from a method in main in Java? If so, how is this possible, and if not, how can we do this?

+48
java
Dec 19 '11 at 6:07
source share
4 answers

You can return a class object in Java.

If you return more than one value that is related to each other, then it makes sense to encapsulate them in a class and then return an object of that class.

If you want to return unrelated values, you can use the built-in java container classes such as Map, List, Set, etc. Check out the java.util JavaDoc package for more details.

+48
Dec 19 '11 at 6:10
source share

You can do something like this:

public class Example { public String name; public String location; public String[] getExample() { String ar[] = new String[2]; ar[0]= name; ar[1] = location; return ar; //returning two values at once } } 
+24
Dec 19 '11 at 6:17
source share

You can return only one value, but it can be an object that has several fields - that is, a "value object". For example,

 public class MyResult { int returnCode; String errorMessage; // etc } public MyResult someMethod() { // impl here } 
+23
Dec 19 '11 at 6:10
source share

Yes you can get multiple values, but you have to combine the value in ArrayLists. I will show you an example and look at the code:

 class mahasiswa{ public String nama; public String nrp; public String sks; public String namakul; public mahasiswa(String nm, String ps, String sk, String nmkul){ this.nama = nm; this.nrp =ps; this.sks = sk; this.namakul = nmkul; } public String getsks(){ return sks; } public String getnamakul(){ return namakul; } public String getnama(){ return nama; } public String getnrp(){ return nrp; } } ArrayList<mahasiswa> myObject; public myArray() { initComponents(); myObject = new ArrayList<mahasiswa>(); for(int i =0;i<myObject.size();i++){ jTextArea1.append("Nama" + " = " + myObject.get(i).getnama() + "\n" + "NRP " + " = " + myObject.get(i).getnrp() + "\n" + "Nama Matakuliah = " + myObject.get(i).getnamakul() + "\n" + "SKS = " + myObject.get(i).getsks() + "\n"); } } 
-four
Dec 19 '11 at 7:05
source share



All Articles