Sobes.tech
Middle

What is a wildcard in Java?

sobes.tech AI

Answer from AI

Wildcard (?) in Java is used in generics to represent an unknown type. It allows working with collections containing elements of various compatible types without strict binding to a specific type.

Main usage scenarios:

  1. ? (Upper Bounded Wildcard): Represents any type that is a subclass or implementation of the specified class/interface. Used for reading data from a collection. Example: List<? extends Number> can contain List<Integer>, List<Double>, .getList<Long>.

    // Reading from a collection with an upper bound
    public void processNumbers(List<? extends Number> numbers) {
        for (Number n : numbers) {
            System.out.println(n);
        }
        // numbers.add(new Integer(10)); // Compilation error - cannot add elements
    }
    
  2. ? super (Lower Bounded Wildcard): Represents any type that is a superclass or the class/interface itself. Used for writing data into a collection (PECS principle: Producer Extends, Consumer Super). Example: List<? super Integer> can contain List<Integer>, List<Number>, List<Object>.

    // Writing into a collection with a lower bound
    public void addIntegers(List<? super Integer> list) {
        list.add(1);
        list.add(new Integer(2));
        // Object o = list.get(0); // Returns Object, as the exact type is unknown
    }
    
  3. ? (Unbounded Wildcard): Represents any type. Equivalent to ? extends Object. Used when the actual type of collection elements is not important, for example, to check size or clear.

    // Working with a collection of any type
    public void printList(List<?> list) {
        for (Object obj : list) {
            System.out.println(obj);
        }
        // list.add("hello"); // Compilation error - cannot add elements (except null)
    }
    

Wildcards increase code flexibility, allowing methods to work with a broader range of collection types while maintaining type safety. They help avoid code duplication for methods performing similar operations on different but compatible collection types.