DEV Community

Aswin Arya
Aswin Arya

Posted on

Difference Between `List<Object>` vs `List<?>` in Java

This is one of the most commonly asked questions in Java Generics interviews. At first glance, both may look similarβ€”but they behave very differently.


πŸ”Ή List<Object>

List<Object> means a list that can hold only Object type (and its subclasses explicitly added as Object).

βœ… Example:

List<Object> list = new ArrayList<>();
list.add("Java");
list.add(10);
list.add(10.5);
Enter fullscreen mode Exit fullscreen mode

βœ” Key Characteristics:

  • You can add any type of object
  • You can read as Object
  • It is a specific type, not flexible

πŸ”Ή List<?> (Wildcard)

List<?> means a list of unknown type.

βœ… Example:

List<?> list = new ArrayList<String>();
Enter fullscreen mode Exit fullscreen mode

βœ” Key Characteristics:

  • It can point to any type of list (List<String>, List<Integer>, etc.)
  • You cannot add elements (except null)
  • You can only read values as Object

πŸ”Ή Core Difference

Feature List<Object> List<?>
Type Specific type Unknown type (Wildcard)
Can hold Only Object list Any type of list
Add elements βœ… Yes ❌ No (except null)
Read elements As Object As Object
Flexibility ❌ Less flexible βœ… More flexible

πŸ”Ή Important Concept

πŸ‘‰ List<Object> is not the parent of List<String>

List<Object> list = new ArrayList<String>(); // ❌ Compile-time error
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ But wildcard works:

List<?> list = new ArrayList<String>(); // βœ… Valid
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Real-Time Understanding

  • Use List<Object> when you want to store different types in the same list
  • Use List<?> when you want to accept any type of list as input (read-only)

πŸ”Ή Interview Tip

πŸ‘‰ If the question is about flexibility β†’ use ?
πŸ‘‰ If the question is about storing mixed data β†’ use Object


πŸš€ Final Thoughts

Understanding the difference between List<Object> and List<?> helps you write more flexible and type-safe Java code, especially when working with APIs and collections.

πŸ‘‰ No 1 Core JAVA Online Training in Hyderabad

Top comments (0)