How to return multiple objects from a Java method?

前端 未结 25 3432
眼角桃花
眼角桃花 2020-11-21 23:55

I want to return two objects from a Java method and was wondering what could be a good way of doing so?

The possible ways I can think of are: return a HashMap<

25条回答
  •  离开以前
    2020-11-22 00:48

    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 {
      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>.

    Also: Why would you want to return a comma-separated list of names instead of a List? Or better yet, return a Map 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.

提交回复
热议问题