Описание тега bounded-wildcard
Bounded wildcard is a type argument of the form "? extends T" or "? super T". Bounded wildcards are a feature of generics in the Java language. These type arguments represent some unknown type, with either an upper or lower bound.
A bounded wildcard is a type argument of the form ? extends T
or ? super T
. Bounded wildcards are a feature of generics in the java language. These type arguments represent some unknown type, with either an upper or lower bound.
A bounded wildcard with an upper bound
? extends T
requires that the original type wasT
or a subtype ofT
:static <T> void fill( Collection<T> collection, int count, Supplier<? extends T> supplier) { for (int i = 0; i < count; ++i) collection.add( supplier.get() ); } List<Number> list = new ArrayList<>(); Supplier<Double> random = Math::random; fill( list, 10, random );
A bounded wildcard with a lower bound
? super T
requires that the original type wasT
or a supertype ofT
:static <T> void forEach( Iterable<T> iterable, Consumer<? super T> consumer) { for (T element : iterable) consumer.accept( element ); } List<Integer> list = Arrays.asList(1, 2, 3); Consumer<Object> printer = System.out::println; forEach( list, printer );
The bounded wildcard ? extends Object
is equivalent to the unbounded-wildcard.
See also:
- Type Arguments of Parameterized Types in the Java Language Specification
- Official wildcards tutorial
- What is PECS (Producer Extends Consumer Super)?