Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query on Generics in java

Tags:

java

generics

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)"

like image 587
kshtjsnghl Avatar asked Dec 29 '22 03:12

kshtjsnghl


2 Answers

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?

like image 139
aioobe Avatar answered Jan 07 '23 13:01

aioobe


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;
like image 32
Bart van Heukelom Avatar answered Jan 07 '23 13:01

Bart van Heukelom