且构网

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

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

更新时间:2023-12-04 14:10:40

如果您想返回两个对象,您通常希望返回一个封装了这两个对象的单个对象.

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

你可以像这样返回一个 NamedObject 对象列表:

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

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

另外:为什么要返回以逗号分隔的名称列表而不是 List?或者更好的是,返回一个 Map ,键是对象的名称和值(除非您的对象已指定顺序,在这种情况下是 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.