Created
December 15, 2013 10:15
-
-
Save jnizet/7971150 to your computer and use it in GitHub Desktop.
Yes, you can add an element from a list to this list, even without knowing its type.
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
import java.util.ArrayList; | |
import java.util.List; | |
public class GenericsFun { | |
public static void main(String[] args) { | |
List<B> bs = new ArrayList<>(); | |
bs.add(new B()); | |
List<? extends A> mix = bs; | |
appendFirstElementToList(mix); | |
System.out.println("mix.size() = " + mix.size()); | |
} | |
private static <T> void appendFirstElementToList(List<T> list) { | |
list.add(list.get(0)); | |
} | |
private static class A { | |
} | |
private static class B extends A { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment