Created
October 1, 2015 19:50
-
-
Save anonymous/adf456f2270836ab454d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import java.util.ArrayList; | |
| import java.util.Collection; | |
| public class CovarianceTest { | |
| public static void main(String[] args) { | |
| Alpha alpha = new Alpha(); | |
| // Type mismatch: cannot convert from element type capture#1-of ? | |
| // extends CovarianceTest.Data to CovarianceTest.Beta | |
| // Quick fix: Change type of beta to Beta. | |
| // That would work, but nasty type casting. | |
| for (Beta beta : alpha.getChildren()) { | |
| System.out.println(beta.getID()); | |
| } | |
| } | |
| public static abstract class Data { | |
| public abstract Collection<? extends Data> getChildren(); | |
| } | |
| public static class Alpha extends Data { | |
| public Collection<Beta> children; | |
| public Alpha() { | |
| this.children = new ArrayList<Beta>(); | |
| this.children.add(new Beta(1)); | |
| this.children.add(new Beta(2)); | |
| this.children.add(new Beta(3)); | |
| } | |
| @Override | |
| public Collection<? extends Data> getChildren() { | |
| return this.children; | |
| } | |
| } | |
| public static class Beta extends Data { | |
| private int id; | |
| public Beta(int id) { | |
| this.id = id; | |
| } | |
| @Override | |
| public Collection<? extends Data> getChildren() { | |
| return null; | |
| } | |
| public int getID() { | |
| return this.id; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment