Interview question
What is the difference between >, extends T>, and super T> wildcards? >, extends T>, और super T> wildcards में क्या अंतर है?
Answer
| Wildcard | Meaning | Can read? | Can write? |
|---|---|---|---|
| > | Unknown type | Yes, as Object | No (except null) |
| extends T> | T or any subtype (upper bound) | Yes, as T | No (except null) |
| super T> | T or any supertype (lower bound) | Yes, as Object only | Yes, as T |
// Unbounded wildcard - accepts a List of ANY type
public static void printList(List<?> list) {
for (Object o : list) {
System.out.println(o); // can only treat elements as Object
}
// list.add('x'); // COMPILE ERROR - can't add anything except null
}
// Upper bounded wildcard - <? extends Number> for READING
public static double sumNumbers(List<? extends Number> list) {
double sum = 0;
for (Number n : list) { // safe to read as Number
sum += n.doubleValue();
}
// list.add(5); // COMPILE ERROR - can't add, compiler doesn't know exact subtype
return sum;
}
sumNumbers(List.of(1, 2, 3)); // works with List<Integer>
sumNumbers(List.of(1.5, 2.5)); // works with List<Double>
// Lower bounded wildcard - <? super Integer> for WRITING
public static void addNumbers(List<? super Integer> list) {
list.add(1); // safe to add Integer or its subtypes
list.add(2);
// Integer i = list.get(0); // COMPILE ERROR - can only read as Object
}
List<Number> numberList = new ArrayList<>();
addNumbers(numberList); // works, Number is a supertype of Integer
// PECS mnemonic: Producer Extends, Consumer Super
// - use 'extends' when the collection PRODUCES data you read
// - use 'super' when the collection CONSUMES data you write| Wildcard | अर्थ | Read? | Write? |
|---|---|---|---|
| > | Unknown type | हाँ, Object की तरह | नहीं |
| extends T> | T या subtype | हाँ, T की तरह | नहीं |
| super T> | T या supertype | सिर्फ Object की तरह | हाँ, T की तरह |
public static void printList(List<?> list) {
for (Object o : list) {
System.out.println(o);
}
// list.add('x'); // COMPILE ERROR
}
public static double sumNumbers(List<? extends Number> list) {
double sum = 0;
for (Number n : list) {
sum += n.doubleValue();
}
// list.add(5); // COMPILE ERROR
return sum;
}
sumNumbers(List.of(1, 2, 3));
sumNumbers(List.of(1.5, 2.5));
public static void addNumbers(List<? super Integer> list) {
list.add(1);
list.add(2);
}
List<Number> numberList = new ArrayList<>();
addNumbers(numberList);
// PECS: Producer Extends, Consumer SuperWas this answer clear?