Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object that returns multiple objects in Java

Tags:

java

object

I want to create an object that will contain and return multiple objects of various types.

What's the best approach for this? There seems to be several ways out there, so I'm interested to hear different peoples' ideas.

Thanks.

like image 674
damien535 Avatar asked Feb 25 '26 08:02

damien535


1 Answers

If you mean to return all of the objects at once, from a single method call, your best bet is to encapsulate all objects into a (possibly inner) class and return an instance of that class.

class Container {
  public static class Container {
    Type1 obj1;
    Type2 obj2;
    ...
  }
  private Type1 obj1;
  private Type2 obj2;
  ...
  public Container getAllObjects() {
    Container container = new Container();
    container.obj1 = this.obj1;
    ...
    return container;
  }
}

(Technically, you could also return multiple objects within an Object[] array, however I don't recommend this for lack of type safety and open possibilities for making ordering errors.)

If you mean to return the objects one by one, from distinct method calls, good old getters are your friends :-)

class Container {
  private Type1 obj1;
  private Type2 obj2;
  ...
  public Type1 getObject1() {
    return obj1;
  }
  public Type2 getObject2() {
    return obj2;
  }
  ...
}
like image 94
Péter Török Avatar answered Feb 26 '26 20:02

Péter Török



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!