Описание тега 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 was T or a subtype of T:

    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 was T or a supertype of T:

    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: