且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Java方法返回多个对象?

更新时间:2023-12-04 14:41:16

如果你想要返回两个对象想要返回一个封装两个对象的单个对象。

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

你可以返回一个 ListdObject的List / code>这样的对象:

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

然后你可以轻松返回 List< NamedObject< WhateverTypeYouWant>>

另外:为什么要返回以逗号分隔的名称列表而不是列表与LT;字符串&GT; ?或者更好的是,返回 Map< String,TheObjectType> ,其中键是对象的名称和值(除非您的对象具有指定的顺序,在这种情况下为 NavigableMap 可能就是你想要的。

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.