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)”
I believe you want to have just
(You can still add subclasses of
WorkTabPaneto 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 aArrayList<WorkTabPaneSubclass1>. However, if that’s the case, then you should not be be allowed to add items of typeWorkTabPaneSubclass2to the list. You see the problem?