Java Object Oriented Design: Returning multiple objects in java
The below code in Java throws Null pointer exception.
public class New{
int i;
New(int i)
{
this.i = i;
}
public void func(New temp)
{
temp.i = 10;
temp = new New(20);
}
public static void main(String[] args)
{
New n = null;
n.func(n);
System.out.println("value "+ n.i);
}
}
The reason being, java passes objects references by value. If I wanted to return one object, then I can return it from the function.
But, If I have multiple objects, the only way I could return the object references is, by keeping them into another object, like having some container which has refe开发者_开发百科rences to all the objects.
Is there a better way to do it?
In C++, I normally just pass the address of pointer to handle this scenario. If I wanted to just return two objects of a single type, creating a container and passing it is a over kill.
What is the problem with returning multiple objects from a function? Why cannot the semantics of the function in all these languages be changed?
Most often you create an object to hold the combination of objects you want to return.
For a more general-purpose solution, you can either return a collection, and array or some sort of tuple, such as Pair, Triple, etc (the latter you will need to create).
Note, you don't generally pass a mutable object as a parameter, but return an immutable one:
public Pair<Integer,Integer> getLowHighTemp() {
int low,hgh;
// do stuff...
return new Pair(low,hgh);
}
This is more of 2 questions than one.
Firstly the problem with your code is that you are not declaring n before you use it. That is throwing the exception.
Secondly if you would like to return 2 objects, you need to have a container object that will hold 2 objects.
You can return some kind of Collection
. Returning a Map
or List
is pretty common.
精彩评论