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.
renisenbbAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mark BullockQA EngineerCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.