Skip to content

Instantly share code, notes, and snippets.

@jnizet
Created December 15, 2013 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnizet/7971150 to your computer and use it in GitHub Desktop.
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.
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