可能重複:
How to return multiple objects from a Java method?如何從Java方法返回多個不同對象?
有沒有辦法從Java方法
比如我想返回字符串,整數,對象返回多個不同模式的對象,.. etc
謝謝
可能重複:
How to return multiple objects from a Java method?如何從Java方法返回多個不同對象?
有沒有辦法從Java方法
比如我想返回字符串,整數,對象返回多個不同模式的對象,.. etc
謝謝
您可以返回一個Map<Class, Object>
,其中包含使用它們的值映射的結果對象的類型。
public Map<Class, Object> doSomeStuff(){
Map<Class, Object> map = HashMap<Class, Object>();
map.put(String.getClass(), "This is an example");
map.put(Object.getClass(), new Object());
//...
return map;
}
// You can then retrieve all results by
String stringVal = map.get(String.getClass());
Object objectVal = map.get(Object.getClass());
這些解決方案哪一個更好?你的或這:http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method – 2014-07-12 12:58:37
他們是一樣的。請注意,您在這裏鏈接到的一個答案最多,表示使用地圖更好 - 這就是我在這裏解釋的答案:) – GETah 2014-07-12 13:58:49
不明確。你可以讓自己的類包含eveything,並返回該類,或者返回包含所有內容的Object
數組(Object[]
)或列表(如ArrayList
),但不建議這樣做。
編輯:你也可以使用上面提到的泛型,這屬於你自己的類的類別,但我認爲我會單獨提及它。
創建一個新類並返回該類。
//Give this a more descriptive name reflecting what it REALLY is.
public static class ReturnData{
protected String foo
protected int bar
public ReturnData(String foo, int Bar) {
...
}
String getFoo() {
...
}
int getBar() {
...
}
然後在你的方法實例與你想要的對象返回
MyMethod(...){
...
...
return new ReturnData(foo, bar);
}
中提琴!你同時返回foo和bar。
目前尚不清楚。 – 2011-12-20 22:52:37
@BeauGrantham我想返回不同的對象 – 2011-12-20 22:56:11