What is the difference between bounded wildcard and type parameters?

They expose different interfaces and contract for the method. The first declaration should return a collection whose elements type is the same of the argument class. The compiler infers the type of N (if not specified). So the following two statements are valid when using the first declaration: Collection<Integer> c1 = getThatCollection(Integer.class); Collection<Double> c2 = … Read more

Java nested generic type

Fundamentally, List<List<?>> and List<? extends List<?>> have distinct type arguments. It’s actually the case that one is a subtype of the other, but first let’s learn more about what they mean individually. Understanding semantic differences Generally speaking, the wildcard ? represents some “missing information”. It means “there was a type argument here once, but we don’t know … Read more

Creating new generic object with wildcard

It’s invalid syntax to instantiate a generic type with wildcards. The type List<? extends Number> means a List of some type that is or extends Number. To create an instance of this type doesn’t make sense, because with instantiation you’re creating something specific: new ArrayList<? extends Number>();//compiler:”Wait, what am I creating exactly?” Generic types with … Read more

Why can’t you have multiple interfaces in a bounded wildcard generic?

Interestingly, interface java.lang.reflect.WildcardType looks like it supports both upper bounds and lower bounds for a wildcard arg; and each can contain multiple bounds Type[] getUpperBounds(); Type[] getLowerBounds(); This is way beyond what the language allows. There’s a hidden comment in the source code // one or many? Up to language spec; currently only one, but … Read more

Java Generics (Wildcards)

In your first question, <? extends T> and <? super T> are examples of bounded wildcards. An unbounded wildcard looks like <?>, and basically means <? extends Object>. It loosely means the generic can be any type. A bounded wildcard (<? extends T> or <? super T>) places a restriction on the type by saying … Read more