Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 494
Gustavo Puma Avatar asked Feb 27 '26 19:02

Gustavo Puma


2 Answers

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.

like image 183
Chris Knight Avatar answered Mar 01 '26 08:03

Chris Knight


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;
}
like image 22
Grodriguez Avatar answered Mar 01 '26 08:03

Grodriguez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!