CKTIS / Java
Lower-bounded wildcard: `? super String`
Learn why `Spliterator<String>.tryAdvance` can take a consumer of `String` or a consumer of a supertype such as `CharSequence`.
Version: Java SE 21
Syntax
? super String
Consumer<? super String>
boolean tryAdvance(Consumer<? super T> action);In Consumer<? super String>, ? stands for an unknown type argument, and super String sets its lower bound. That argument can be String itself or a supertype such as CharSequence or Object. This does not make Consumer<Object> a subtype of Consumer<String>: without the wildcard, neither parameterization is assignable to the other.
Through a Consumer<? super String> reference, you can call accept with a String, but not with an arbitrary Object or a StringBuilder: the actual consumer might accept only String. By contrast, Consumer<? extends CharSequence> does not guarantee that accept can take a String, since its unknown type argument might be StringBuilder. Use super when you pass values into a consumer (the consumer super part of PECS).
In Spliterator<T>, the method boolean tryAdvance(Consumer<? super T> action) takes a Consumer<? super String> when T = String. If an element remains, the method passes one element to the action and returns true if the action completes normally; for an ORDERED spliterator, it uses the next element in encounter order. If no elements remain, it returns false without invoking the action.
A null action causes a NullPointerException. If the action throws an exception, it propagates to the caller, and the spliterator's subsequent behavior is unspecified.
Examples
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Spliterator<String> words = List.of("Java").spliterator();
Consumer<CharSequence> printLength = text -> System.out.println(text.length());
Consumer<? super String> action = printLength;
System.out.println(words.tryAdvance(action));
System.out.println(words.tryAdvance(action));
}
}Result
4 true false
A `Consumer<CharSequence>` can handle a `String` without a cast. The first call prints the length of `Java` (`4`) before `true` is printed; the second prints `false` and does not run the action.
Related lessons
- Java · Lesson 23 · Advanced · Version: 2