Instantiating two objects inside a method for use as 'return values'
I've got the following class:
public class Matriz
{
...
static public void create(Matriz a, Matriz b)
{
...
a=new Matriz(someValue,anotherValue);
b=new Matriz(someValue,anotherValue);
...
}
}
And in my main method:
public static void main(String[] args)
{
Matriz a=null,b=null;
Matriz.create(a,b);
//these are null
a.print();
b.print();
}
开发者_高级运维
The point of my method create() is to "return" two Matriz objects. How could I do this?
Here are a few suggestions:
1) Return a list of them:
public List<Matriz> create(..);
...
List<Matriz> matrizList = Matriz.create(...);
a = matrizList.get(0);
b = matrizList.get(1);
2) Return a method Object
public MatrizHolder create(...);
...
MatrizHolder holder = Matriz.create(...);
a = holder.getA();
b = holder.getB();
3) Create them one at a time
public Matriz create(...);
...
a = Matriz.create(..);
b = Matriz.create(..);
As an aside, you can't pass a null reference to a method, have it initialized in a method and retain the reference when the method completes. Hence, passing a and b to the create method in your code above doesn't make sense.
The simplest way is to just return an array:
static public Matriz[] create()
{
...
Matriz[] m = new Matriz[2];
m[0] = new Matriz(someValue, anotherValue);
m[1] = new Matriz(someValue, anotherValue);
...
return m;
}
Either return an array of the two:
public static Matriz[] create(..) {
...
return new Matriz[] {a, b};
}
or introduce a new class -
class MatrizPair {
private Matriz a;
private Matriz b;
// setter and getter for each
}
It's important to note that your example does not work because java is "pass-by-value", rather than "pass-by-reference" (read this)
This kind of thing won't work in Java, because Java calls by value, not by reference.
What you can do if you want this functionality is to pass a container of any kind to the method (an array, a Collection, an AtomicReference etc., but you can't do it just by using a variable. The variable is copied when passed into the method, so the original value can't be changed by the method. If you do pass a container, you can insert a value from the method, and that will be visible from the original context because the outer method points to the same container object (the references are copied, but the values aren't).
Firstly, you should not be passing in the objects you want to instantiate. Just return an array.
So your code would look like this
public class Matriz
{
...
static public Matriz[] create()
{
...
a=new Matriz(someValue,anotherValue);
b=new Matriz(someValue,anotherValue);
...
return new Matriz[] {a, b};
}
}
And your main method:
public static void main(String[] args)
{
Matriz[] array = Matriz.create();
array[0].print();
array[1].print();
}
You can't return two object. You can return only array or collection of objects. In your case you can make variables as class fields and assign something to them in 'create' method
精彩评论