Return to site

💡 Can you pass a List〈String〉 to a method that accepts List〈Object〉?

August 31, 2025

❌ No, you can’t.
Even though String is a subtype of Object, List〈String〉 is NOT a subtype of List〈Object〉 in Java.

This is because generics are invariant — List〈A〉 is not related to List〈B〉, even if A extends B.

🔍 Why?
If it were allowed, you could insert any Object (e.g., Integer) into the List〈String〉, breaking type safety.

🛠 Solution:
Use wildcards if you want flexibility:
void printList(List〈?〉 list) { ... } // Any type
void printList(List〈? extends Object〉 list) { ... } // Any object type

💡 Generics protect your collections by preventing unsafe assignments.

#Java #JavaInterview #Generics #TypeSafety #List #JavaTips #OOP #CodingInterview #interviewprep

Go further with Java certification:

Java👇

https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A

Spring👇

https://www.udemy.com/course/spring-professional-certification-6-full-tests-2v0-7222-a/?referralCode=04B6ED315B27753236AC