Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java (1.6) generics wildcard

Tags:

java

generics

Consider flowing situation:

    class A {

    }

    class B extends A {

    }


    List <? extends A> x = new ArrayList<A>();
    List <? extends A> xx = new ArrayList<B>();

both 'x' and 'xx' are legal declarations in Java 6 and Java 7 (I know that in Java 7 you can also substitute the parameterized type of the constructor with an empty set of type parameters (<>). However, I wonder, what is the difference between 'x' and 'xx' in Java 6?

like image 269
whiteErru Avatar asked Dec 10 '13 13:12

whiteErru


People also ask

What is wildcard in Java generic?

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).

How do you use generic wildcards?

The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.

Why do we need wildcard in generics in Java?

We can use the Java Wildcard as a local variable, parameter, field or as a return type. But, when the generic class is instantiated or when a generic method is called, we can't use wildcards. The wildcard is useful to remove the incompatibility between different instantiations of a generic type.

Can return type be wildcard?

Do not use wildcard types as return types.


Video Answer


2 Answers

The way you wrote it, there is no difference.

At compile-time, both have the same type; namely, a List<> of some unknown type that extends A.
This is why you can't add anything to either list – you have no idea whether it's actually a List<B> or a List<C> or of some other type.

At runtime, they also have the same type; namely, List. Due to type erasure, the type parameter doesn't exist at runtime.

Because you don't save any more strongly-typed references to it, no-one can tell that one of the lists is actually a List<B>.

The point of these wildcards is for functions.
You can make a function that takes a List<? extends A>, then pass it a List<B> or a List<C>, and the calling code can keep using the original list with its original type.

like image 89
SLaks Avatar answered Oct 20 '22 16:10

SLaks


no difference. it all boils down to two lists of objects. You are just trying to coax the compiler to lend you a helping hand, as it's quite clever and could help you catch bad usage. You tell it that as long as the type in the List is-a A, all is fine. The compiler can then help highlighting any problems.

like image 39
Peter Perháč Avatar answered Oct 20 '22 14:10

Peter Perháč