Last active
November 29, 2019 10:16
-
-
Save calaveraInfo/9f6982aba71d05cfa740496064a2e61c to your computer and use it in GitHub Desktop.
Wildcards in "indirect" or "second level" generics.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package x; | |
/** | |
* <p> | |
* Wildcards in "indirect" or "second level" generics. | |
* <p> | |
* {@link #list} contains generic items. | |
* {@link #testWildcard()} and {@link #testGeneric()} wants to work with that items | |
* and shouldn't care about it's generic type <i>as long as it's the same type through the | |
* whole method<i>. How to express that correctly (if it's possible at all)? | |
* | |
* Solution: {@link #testWithHelper()} | |
*/ | |
public class CovarianceTest { | |
private List<ListItem<? extends Number>> list = Arrays.asList(new ListItem<>(1l), new ListItem<>(1d)); | |
@Test | |
public void testWildcard() { | |
ListItem<?> listItem = list.get(0); | |
ListItemService<?> service = new ListItemService<>(listItem.getData()); | |
// compile error | |
// listItem.setService(service); | |
} | |
@Test | |
public <T extends Number> void testGeneric() { | |
// ugly with unchecked warning | |
ListItem<T> listItem = (ListItem<T>) list.get(0); | |
ListItemService<T> service = new ListItemService<>(listItem.getData()); | |
listItem.setService(service); | |
} | |
@Test | |
public void testWithHelper() { | |
initHelper(list.get(0)); | |
} | |
private <T extends Number> void initHelper(ListItem<T> listItem) { | |
ListItemService<T> service = new ListItemService<>(listItem.getData()); | |
listItem.setService(service); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package x; | |
public class ListItem<T extends Number> { | |
private T data; | |
private ListItemService<T> service; | |
public ListItem(T data) { | |
this.data = data; | |
} | |
public T getData() { | |
return data; | |
} | |
public void setService(ListItemService<T> service) { | |
this.service = service; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package x; | |
public class ListItemService<T extends Number> { | |
private T data; | |
public ListItemService(T data) { | |
this.data = data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment