2011-12-20 147 views

回答

5

您可以返回一個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()); 
+0

這些解決方案哪一個更好?你的或這:http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method – 2014-07-12 12:58:37

+0

他們是一樣的。請注意,您在這裏鏈接到的一個答案最多,表示使用地圖更好 - 這就是我在這裏解釋的答案:) – GETah 2014-07-12 13:58:49

1

不明確。你可以讓自己的類包含eveything,並返回該類,或者返回包含所有內容的Object數組(Object[])或列表(如ArrayList),但不建議這樣做。

編輯:你也可以使用上面提到的泛型,這屬於你自己的類的類別,但我認爲我會單獨提及它。

1

創建一個新類並返回該類。

//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。