Generic request in java

I recently started using generics in java, and in this attempt I tried to reorganize the existing code of our team.

Can someone tell me what's 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 on line 3 (when adding) - "The add (capture # 1-of? Extends WorkTabPane) method in the ArrayList type is not applicable for arguments (T)"

+4
source share
2 answers

I believe that you just want

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

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

The reason eclipse complains is this: by writing <? extends WorkTabPane> <? extends WorkTabPane> , you say: "This is a list of some specific class that extends to WorkTabPane." This variable may contain, for example, a reference to ArrayList<WorkTabPaneSubclass1> . However, if this happens, you should not be allowed to add items like WorkTabPaneSubclass2 to the list. Do you see the problem?

+8
source
 private ArrayList<? extends WorkTabPane> workTabPanes = null; 

This says that workTabPanes is a list that is guaranteed to contain instances of WorkTabPane or one of its subclasses, so when you read it, you know what you get. However, it may be a list of WorkTabPaneSub s to which you cannot add regular WorkTabPane s.

You need:

 private ArrayList<WorkTabPane> workTabPanes = null; 
+2
source

Source: https://habr.com/ru/post/1332924/


All Articles