如何从Java方法返回多个对象? [英] How to return multiple objects from a Java method?
问题描述
我想从Java方法返回两个对象,并想知道这样做的好方法是什么?
I want to return two objects from a Java method and was wondering what could be a good way of doing so?
我能想到的可能方法是:返回 HashMap
(因为这两个对象是相关的)或返回对象的
ArrayList
/ code> objects。
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.
你可以返回一个 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;字符串>
?或者更好的是,返回 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.
这篇关于如何从Java方法返回多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!