2014-06-16 40 views
0

我目前正試圖重構我的一些代碼,並且偶然發現了我以前在Java中與泛型相關的一個功能。使用泛型返回多個類型

我試圖根據傳入方法的參數返回一個特定類型的ArrayList<?>。該參數接受指定的ArrayList<T>所需類型的返回,這樣的事情是一個枚舉,但我從方法原型得到錯誤:

// Retrieves an ArrayList of questions available for a particular QuestionType 
    public <T extends Question> ArrayList<T extends Question> getQuestions(QuestionType type) { 
     switch (type) { 
     case BASE_QUESTION: 
      return mQuestions; // ArrayList<Question> 

     case MULTIPLE_ANSWER_QUESTION: 
     case MULTIPLE_CHOICE_QUESTION: 
     case TRUE_FALSE_QUESTION: 
      return mMultipleAnswerQuestions; // ArrayList<MultipleAnswerQuestion> 

     case MATCHING_QUESTION: 
      return mMatchingQuestions; // ArrayList<MatchingQuestion> 

     case BLANK_QUESTION: 
      return mBlankQuestions; // ArrayList<BlankQuestion> 

     default: 
      // TODO Perfect place to throw an exception 
      Log.d(TAG, "Exception: Provided a non-existant QuestionType"); 
     } 
    } 

附加信息: 中包含多個自定義對象中存在這種方法按其類型組織的問題ArrayList。此方法不存在於Question類型的SuperClass中。

// CLASS HIERARCHY 
// SuperClass 
Question 

// SubClasses of Question 
MultipleAnswerQuestion 
MultipleChoiceQuestion 
TrueFalseQuestion 
MatchingQuestion 
BlankQuestion 

有些人可以向我解釋如何爲實現此任務的方法建立原型嗎?

感謝您的理解和幫助。

+1

您不需要在返回類型中再次指定'extends Question'。你已經指定了。此外,在這種情況下,似乎通配符可能會更好,因爲您不使用'T' – awksp

+0

您能否提供一個答案來演示此方法? – Matt

+0

你有什麼錯誤? – shmosel

回答

2

你有很可能,因爲在聲明上T邊界第二次的語法錯誤,不認識ArrayList<T extends Question>爲您的返回類型防止編譯那些特定的編譯錯誤。因此,如果您刪除extends Question或將您的返回類型更改爲有界通配符,編譯錯誤應該消失。

在通用方法中,只能在類型參數上指定邊界一次 - 在方法簽名的開頭聲明它們時。換句話說,只需使用ArrayList<T>作爲返回類型而不是ArrayList<T extends Question>,因爲您已經指定了泛型方法中T的界限。

所以你最終的東西,如

public <T extends Question> ArrayList<T> getQuestions(QuestionType type) { 
    ... 
} 

此外,因爲你沒有出現真正使用T在你的方法,它可能是一個更好的主意完全跳過泛型方法只需在返回值中使用有界通配符,如下所示:

public ArrayList<? extends Question> getQuestions(QuestionType type) { 
    ... 
} 
2

你的方法的簽名更改爲:

public ArrayList<? extends Question> getQuestions(QuestionType type) 

在一個側面說明,你可能想只是創建一個EnumMap映射你的列表,而不是在做每次switch

+1

提及'EnumMap' – awksp

1

正確的原型是public <T extends Question> ArrayList<T> getQuestions(QuestionType type)public ArrayList<? extends Question> getQuestions(QuestionType type)