• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 265
  • Last Modified:

Java: want to return 2 values from a method

I have a method, and i want to return an int from it, and also an object of a Employee class.
The int and the Employee object are not related, so i thought HashMap was not suitable.
I was thinking of returning an Object array, but not sure if there's a better way.
0
renisenbb
Asked:
renisenbb
1 Solution
 
Mark BullockQA Engineer IIICommented:
You have to do something like you suggested.
However int is not an object. You can use Integer.

I might suggest that your method is doing too many things. Or perhaps you need a new object if these two things are truly related.
0
 
dpearsonCommented:
I find a class like this to be very helpful:

public class Pair<T1, T2> {
	private final T1 m_Value1 ;
	private final T2 m_Value2 ;
	
	public Pair(T1 value1, T2 value2) {
		m_Value1 = value1 ;
		m_Value2 = value2 ;
	}
	
	public T1 getValue1() { return m_Value1 ; }
	public T2 getValue2() { return m_Value2 ; }
}

Open in new window

Which you can then use like this:

public Pair<Integer, Employee> computeSomething() {
    ...

    return new Pair<Integer, Employee>(10, employee) ;
}

Open in new window


The advantage of a little class like this is that it's type safe when you pull the values out of the result:

Pair<Integer, Employee> result = computeSomething() ;
int pay = result.getValue1() ;
Employee employee = result.getValue2() ;

Open in new window

If you use a Map or an Object array you will end up having to cast the values.  This way you have no cast and there's compile time checking that everything matches up.

Doug

P.S. You only need one Pair class - it will then work for any time you need to return 2 values from a method.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Tackle projects and never again get stuck behind a technical roadblock.
Join Now