Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 4 of 10 · Java Generics & Type Safety
Interview question

What is the difference between , , and wildcards? , , और wildcards में क्या अंतर है?

Answer
WildcardMeaningCan read?Can write?
Unknown typeYes, as ObjectNo (except null)
T or any subtype (upper bound)Yes, as TNo (except null)
T or any supertype (lower bound)Yes, as Object onlyYes, 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 की तरहनहीं
T या subtypeहाँ, 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 Super

Was this answer clear?