Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In Java, arrays are covariant (i.e. Integer[] is an Object[]), but generic collections are invariant. For example, even though Integer is a subclass of Number, a List<Integer> is NOT a List<Number>.
To provide flexibility in API design while preserving complete type safety, Java provides Wildcards (?).
Consider this method:
If Java allowed this, you could write list.add(45.50); inside the method, which would illegally corrupt an Integer list with a Double!
<?>)Represents any arbitrary type:
<? extends T>)Restricts the unknown type to be either type T or a subtype of T. Used when you want to read/produce values from a structure:
<? super T>)Restricts the unknown type to be either type T or a supertype of T. Used when you want to write/consume values into a structure:
The golden rule of Java Generics coined by Joshua Bloch in Effective Java:
Collections.copy:src produces items for the algorithm (? extends T).dest consumes items from the algorithm (? super T).Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 1 questions. Each question has one correct answer.