I was trying some sample programs on Generics Upper/Lower bounds.. Generics Upper Bound is giving compilation error...But Lower Bound is fine. I am just trying to put a List of type T into a set and try both Upper and Lower bound scenarios..
Please help to identify the issue with testUpperBound(T t) method and why exactly does the testLowerBound(T t) method compile and the testUpperBound(T t) one doesn't. I checked other similar threads..But still I haven't got it clear.
Please Let me know if need more details .
public class TestGenerics<T>
{
public static void main(String...args)
{
List<String> list = new ArrayList<>();
list.add("New ArrayList");
new TestGenerics<List<String>>().testUpperBound(list);
new TestGenerics<List<String>>().testLowerBound(list);
}
public void testLowerBound(T t)
{
Set<? super ArrayList<T>> lowerBoundSet = new HashSet<>();
lowerBoundSet = new HashSet<List<T>>();
ArrayList<T> list = new ArrayList<>();
list.add(t);
lowerBoundSet.add(list); // compiles..
out.println(lowerBoundSet);
}
public void testUpperBound(T t)
{
Set<? extends List<T>> upperBoundSet = new HashSet<>();
upperBoundSet = new HashSet<List<T>>();
ArrayList<T> list = new ArrayList<>();
list.add(t);
upperBoundSet.add(list); // Doesn't compile..
out.println(upperBoundSet);
}
}