How to return multiple objects from a Java method?

If you want to return two objects you usually want to return a single object that encapsulates the two objects instead.

You could return a List of NamedObject objects like this:

public class NamedObject<T> {
  public final String name;
  public final T object;

  public NamedObject(String name, T object) {
    this.name = name;
    this.object = object;
  }
}

Then you can easily return a List<NamedObject<WhateverTypeYouWant>>.

Also: Why would you want to return a comma-separated list of names instead of a List<String>? Or better yet, return a Map<String,TheObjectType> with the keys being the names and the values the objects (unless your objects have specified order, in which case a NavigableMap might be what you want.

Leave a Comment