如何从 Java 方法返回多个对象? [英] How to return multiple objects from a Java method?

查看:29
本文介绍了如何从 Java 方法返回多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Java 方法返回两个对象,并且想知道这样做的好方法是什么?

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

我能想到的可能方式是:返回一个HashMap(因为两个Objects是相关的)或者返回一个ObjectArrayList对象.

The possible ways I can think of are: return a HashMap (since the two Objects are related) or return an ArrayList of Object objects.

更准确地说,我要返回的两个对象是 (a) List 对象和 (b) 以逗号分隔的相同名称.

To be more precise, the two objects I want to return are (a) List of objects and (b) comma separated names of the same.

我想从一个方法返回这两个对象,因为我不想遍历对象列表来获取逗号分隔的名称(我可以在此方法的同一循环中执行此操作).

I want to return these two Objects from one method because I dont want to iterate through the list of objects to get the comma separated names (which I can do in the same loop in this method).

不知何故,返回一个 HashMap 看起来不是一种非常优雅的方式.

Somehow, returning a HashMap does not look a very elegant way of doing so.

推荐答案

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

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.

这篇关于如何从 Java 方法返回多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆