我目前正試圖重構我的一些代碼,並且偶然發現了我以前在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
有些人可以向我解釋如何爲實現此任務的方法建立原型嗎?
感謝您的理解和幫助。
您不需要在返回類型中再次指定'extends Question'。你已經指定了。此外,在這種情況下,似乎通配符可能會更好,因爲您不使用'T' – awksp
您能否提供一個答案來演示此方法? – Matt
你有什麼錯誤? – shmosel