Tell me, please, how to return a List containing objects of two classes?

There are objects of the classes Profession and Subject

 List<Profession> и List<Subject> 

How in a method to return them one list?

  • Either make Profession and Subject inherit from a common ancestor, or declare the list as List <Object>. - Sergey Gornostaev
  • Why do you need it? You should not want this. Maybe you need to pack objects in pairs in a container class? - VladD
  • I implement ServiceRest to return database data in JSON format. @ VladD - Nadezhda

1 answer 1

Alternatively, use the Object class:

 List<Object> objList = new ArrayList<>(); objList.addAll(professionList); objList.addAll(subjectList); 

Another way is to create a class that encapsulates these two lists:

 class Storage { private List<Profession> professions; private List<Subject> subjects; public Storage(List<Profession> professions, List<Subjects> subjects) { ... } ... } 

And further we return List<Storage> .

In general, most likely, your method is implemented incorrectly, since it is required to return lists of two different classes.

  • Or use one of the implementations of the class Pair - rjhdby
  • Well, actually this is the same Storage class, but in a generalized form - Pavel Parshin
  • In Pair, the objects will still be in pairs, and in your implementation there will simply be two unbound sheets. - rjhdby