·
❌ 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👇
Spring👇