damien535
damien535

Reputation: 637

Create an object that returns multiple objects in Java

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.

Upvotes: 3

Views: 3204

Answers (5)

Reza
Reza

Reputation: 1577

Isn't this the definition of all Collection Objects (and most implementations of List interface like ArrayList)?

A collection object contains other objects and return them through a method call?

Upvotes: 1

Péter Török
Péter Török

Reputation: 116266

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;
  }
  ...
}

Upvotes: 4

Jason Rogers
Jason Rogers

Reputation: 19344

Well there are 3 ways I can see for you:

-1) use the fact that variable passed are passed by reference. this way you can modify directly the object in your function and not have to worry about return values

-2) you can simple create a array of objects:

Object[] returnTab = new Object[numberToStore];

(this is not very pretty I find)

-3) create a ReturnObjectContainer object

public class container { public ObjectA a; public ObjectB b;

Arraylist list = new list();

... //add whatever you need to store }

Upvotes: 2

Nanne
Nanne

Reputation: 64409

What do you mean by "return"? As far as I understand the terms, objects don't return anything, they just are. They can have getters that return an object ofcourse. Could you tell me what several ways you're talking about?

If I understand you correctly you'd just want a class (object) with several private objects (variables) that can be set and gotten trough functions (members).

Upvotes: 1

Mihai Toader
Mihai Toader

Reputation: 12243

Make a class similar to this:

class ReturnValue {
   Type1 value1;
   Type2 value2;
}

and return an instance if it from your method if you know what types you want to return all the time.

If you don't know then the only way is to return an Object[] containing your values.

Upvotes: 2

Related Questions