kshtjsnghl
kshtjsnghl

Reputation: 601

Query on Generics in java

I have recently started using generics in java, and in that attempt tried to refactor existing code of our team.

Can anyone please tell me what is wrong with the following -

private ArrayList<? extends WorkTabPane> workTabPanes = null;
protected <T extends WorkTabPane> void addPane(T pane) {
    workTabPanes.add(pane);
}

Eclipse indicates an error at line 3(at add) - "The method add(capture#1-of ? extends WorkTabPane) in the type ArrayList is not applicable for the arguments (T)"

Upvotes: 4

Views: 146

Answers (2)

aioobe
aioobe

Reputation: 421030

I believe you want to have just

private ArrayList<WorkTabPane> workTabPanes = null;
protected void addPane(WorkTabPane pane) {
    workTabPanes.add(pane);
}

(You can still add subclasses of WorkTabPane to the list.)

The reason eclipse complains is the following: By writing <? extends WorkTabPane> you say "This is a list of some specific class which happens to extend WorkTabPane". This variable could for instance contain a reference to a ArrayList<WorkTabPaneSubclass1>. However, if that's the case, then you should not be be allowed to add items of type WorkTabPaneSubclass2 to the list. You see the problem?

Upvotes: 8

Bart van Heukelom
Bart van Heukelom

Reputation: 44104

private ArrayList<? extends WorkTabPane> workTabPanes = null;

This says workTabPanes is a list that is guaranteed to contain instances of WorkTabPane or one of its subclasses, so when reading from it you know that's what you get. It may however be a list of WorkTabPaneSubs, in which you can't put regular WorkTabPanes.

You need:

private ArrayList<WorkTabPane> workTabPanes = null;

Upvotes: 2

Related Questions