Java Generics Wildcards Interview Questions and Answers

Java generics wildcard interview questions: List<Object> vs List<String>, extends vs super bounds, the PECS rule, and when to use an unbounded wildcard.

Generics Wildcards

Module: Generics and Collections
Topic: Generics Wildcards


📋 Table of Contents

for (Object val : vals) { System.out.println ("read: " + val); } }


🔹 Q5: Where will you apply the wild card “ ? super T “?

Answer:

If you were to add the following method to “GenericSingleT ypeScenario.java” The following code will compile.mport java.util.ArrayList ; mport java.util.List; public class GenericSingleT ypeScenarioT est { public static void main (String [] args) { GenericSingleT ypeScenario listOfInts = new GenericSingleT ypeScenario (); listOfInts .add(1); // can add Number or subclasses of Number

List fruits = new ArrayList (); fruits .add("Apple" );

listOfInts .read(fruits ); } public void add(List<? super T> list, T val) { vals.add(val); }

Output: The following code without the wildcard “? super T”mport java.util.ArrayList ; mport java.util.List; public class GenericSingleT ypeScenarioT est { public static void main (String [] args) { GenericSingleT ypeScenario listOfInts = new GenericSingleT ypeScenario (); listOfInts .add(2);

List doubles = new ArrayList (); doubles .add(5.0);

listOfInts .add(doubles, 6);

System.out.println (doubles ); } 5.0, 6]

will throw a compile error as shown below as “ T” is an “Integer” and List cannot be assigned to add(…..) method’ s first argument List But it will be able to assigned to List<? super Integer> as “Number” is a super class of “Integer”. Have you completed this unit? Then mark this unit as completed. Mark as Completed « Previous Unit Next Unit »public void add(List list, T val) { list.add(val); } mport java.util.ArrayList ; mport java.util.List; public class GenericSingleT ypeScenarioT est { public static void main (String [] args) { GenericSingleT ypeScenario listOfInts = new GenericSingleT ypeScenario (); listOfInts .add(2);

List doubles = new ArrayList (); doubles .add(5.0);

listOfInts .add(doubles, 6 // !!!! COMPILE ERROR

System.out.println (doubles ); }


Source: Extracted from PDF Last Updated: 2026-06-03


📚 Related Topics


💡 Key Takeaways

Review the questions above and ensure you understand:

  • Core concepts and their practical applications
  • Real-world scenarios and use cases
  • Best practices and common pitfalls

⬆ Back to Top

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.