Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to return multiple values from one method??

Status
Not open for further replies.

Bartec

Programmer
Jan 21, 2005
54
PL
Hi!

I'm quite new in Java, so please tell me how I can return multiple values from one method? In C++ I uses pointers but what about java?? Thanks for any advise and help.

Best regards

Bartec

 
In short, you cannot.

If you really need to "return" more than one value, you need to set up a data holder, eg :

Code:
class DataHolder {
  public int anInt = -1;
  public String aString = null;
}

And then in your method :

Code:
public DataHolder myMethod() {
  DataHolder dh = new DataHolder();
  dh.anInt = 9;
  dh.aString = "Hello";

  return dh;
}

Then your calling method unpacks the DataHolder class :

Code:
DataHolder dataHolder = myMethod();
int i = dataHolder.anInt;
String s = dataHolder.aString;

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
You can obviously only return one thing from a method. If you want to return several values, then you could define a class to hold these values and return an instance of it from the method.
Code:
public class MyReturnValue {
  private int value1;
  private int value2;

  public MyReturnValue(int val1, int val2){
    this.value1 = val1;
    this.value2 = val2;
  }

  public int getValue1(){
    return value1;
  }

  public int getValue2(){
    return value2;
  }
}

Then this would be used :-

public class SomeClass {

  public MyReturnValue doSomething(){
    //... do some stuff
    return new MyReturnValue(1,2);
  }
}

This would return values 1 and 2, held in the instance of MyReturnValue. You can obviously substitute the 1 and 2 for other values, perhaps from variables. Change the MyResultValue class to hold values of the types you want.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
sedj, we're doing that 'simultaneous reply' thing again [bigsmile]!

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
I'm gonna have to register a new username that starts with a letter before S in the alphabet. Then this forum might put me first, eh?

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
I think it's by age.

Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
Oh dear, I'm scuppered then!

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top