Questions tagged [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 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 .

See also:

243 questions
-1
votes
1 answer

How to remove 'unchecked' warning from my method?

I have following code private static class ParcelableParser { private ArrayList parse(List parcelables) { ArrayList parsedData = new ArrayList(); for(Parcelable parcelable : parcelables) { …
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
-1
votes
4 answers

method argument suitable for adding to a upper-bound ArrayList

the following code is part of an abstract class which is meant to be subclassed to manage a specific kind of Shape. (it's actualy a repository for a specific class but that's not relevant now) protected ArrayList
Midge
  • 51
  • 3
-3
votes
2 answers

How to call this generic function?

I have tried many ways to call the countGreaterThan() function (described here), but I am unable to get it to work. I understand I need to use Integer instances and not primitives. This is what I've tried: MainClass.java public class MainClass…
1 2 3
16
17