2014-09-19 91 views
0

我知道很多人问这样的问题,但我真的没有得到这个。Java泛型编译错误 - 不明白错误

(如果你需要更多的代码,请告诉)

public class QuestionManager<Question extends Component & IQuestion<? extends IAnswerStorage>> 

public class AccountingQuestionManager<Question extends Component & IQuestion<? extends IAnswerStorage>> extends QuestionManager<Question> 

public interface IQuestion<DataStorage extends IAnswerStorage> 

IAnswerStorage是一个空的接口

这是我3泛型类,我需要解释。在QuestionManager问题需要问题(IQuestions)[与指定存储]

我现在尝试以下,希望它允许任何问题,这也是组件。

QuestionManager<? extends Component & IQuestion<? extends IAnswerStorage>> manager = new AccountingQuestionManager<>(
      "Test test", this); 

我也有一个功能问题增加的问题,池:

manager.addQuestion(question); 

,但我得到了2个以下错误:

Incorrect number of arguments for type QuestionManager<Question>; it cannot be parameterized with arguments <? extends Component, IQuestion<? extends IAnswerStorage>> 
Syntax error on token "&", , expected 

太感谢很多为你的帮助。让我知道你是否需要更多。

回答

-1

声明变量时,不能在泛型部分使用'&'。它只适用于声明泛型类。当声明使用泛型类的变量/字段时,始终为泛型参数提供具体的类/接口。 例如,QuestionManager<Question>

+0

你可以使用'&'http://docs.oracle.com/javase/tutorial/java/generics/bounded.html – FazoM 2014-09-19 15:18:51

+0

哦,我的坏。我会修改答案 – SirRichie 2014-09-19 15:19:56

+0

自'QuestionManager'何时有两个类型参数? – bcsb1001 2014-09-19 15:24:16

1

在这个表达式中

public class QuestionManager<Question extends Component & IQuestion<? extends IAnswerStorage>> 

您正在声明一个类型参数命名Question这是ComponentIQuestion<? extends IAnswerStorage>子类型。也就是说,类型参数Question有多个边界。

在此表达

QuestionManager<? extends Component & IQuestion<? extends IAnswerStorage>> manager = new AccountingQuestionManager<>("Test test", this); 

你正在试图做的是声明一个类参数QuestionManager类型。一个类型参数不能被声明为有多个边界。根据定义,类型参数已经是一个具有任何边界的类型。你不能在表达式中重新定义它。

Here are the syntax rules for type arguments.

1

您可以在声明中使用的通用&,但不是在变量分配。您可以放心地做

QuestionManager<?> manager = //... 

,因为它在类型参数Question,它已经将适合? extends Component & IQuestion<? extends IAnswerStorage>的规格保证。

+0

嗨, 这不起作用 – 2014-09-21 09:38:06

+0

@ Reisi007它不起作用?使用我的解决方案时遇到什么问题? – bcsb1001 2014-09-21 10:32:06

+0

如果我使用,那么addQuestion(Question)的类型是?。而且我无法添加类型“?”中的任何内容。谢谢你的尝试,但Java对此不够聪明。无论如何,我找到了一个工作解决方案 – 2014-09-21 11:41:29

0

所以这是我能解决我的具体问题(我不能够,如果我会少些通用) QuestionManager方式:

public class QuestionManager<Question extends IQuestion<? extends AnswerStorage>> 

延伸ExtBorderLayout

而且“addQuestion”方法如下所示

public <QuestionComponent extends IQuestion<? extends AnswerStorage> & Component> void addQuestion(
     QuestionComponent question) 

所以,使方法通用为我做了工作。

感谢您的帮助!