Create an object that returns multiple objects in Java

I want to create an object that will contain and return several objects of different types.

What is the best approach for this? It seems that there are several ways, so I'm interested in hearing the ideas of different peoples.

Thank.

+3
source share
5 answers

If you want to return all objects at once, from one method call, it is best to encapsulate all objects in a (possibly internal) class and return an instance of this 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 can also return multiple objects in an array Object[], however, I do not recommend this because of the lack of type safety and open possibilities for creating order errors.)

, , - : -)

class Container {
  private Type1 obj1;
  private Type2 obj2;
  ...
  public Type1 getObject1() {
    return obj1;
  }
  public Type2 getObject2() {
    return obj2;
  }
  ...
}
+3

:

class ReturnValue {
   Type1 value1;
   Type2 value2;
}

, , , .

, - Object[], .

+2

, 3 :

-1) , .

-2) :

Object[] returnTab = new Object[numberToStore];

( )

-3) ReturnObjectContainer

{  public ObjectA a;  public ObjectB b;

Arraylist = ();

... // , }

+2

What do you mean by "return"? As far as I understand the terms, objects do not return anything, they just are. They can have getters that return an object. Could you tell me what are some of the ways you speak?

If I understand you correctly, you just need a class (object) with several private objects (variables) that you can set and get functions (members).

+1
source

Isn't that the definition of all Collection objects (and most implementations of the List interface, such as ArrayList)?

Does the collection object contain other objects and return them through a method call?

+1
source

Source: https://habr.com/ru/post/1786093/


All Articles