Difference between List, List<?>, and List<Object> in Java
A popular Java interview question based on Generics and Collection
Hello guys, since you guys like How ConcurrentHashMap works in Java and Why String is Immutable in Java, I am back with another core Java interview question for this week.
What is the difference between List, List<?>, and List<Object> in Java?
This is another tricky question that is commonly asked to Java programmers with few years of experience to test their knowledge about Generics and Collections. While they look really similar, there are subtle differences between them and it requires good knowledge of Java to answer this question.
By the way, if you like to receive Java interview questions twice a week in your email, please consider getting a paid subscription, it’s just $5 per month, thank you for your support.
Coming back to topic, In Java, List
, List<?>
, and List<Object>
represent different concepts and have different meanings:
List
This refers to a raw type of a list. It's a generic interface that represents an ordered collection of elements. However, when you useList
without specifying a type parameter (e.g.,List<Integer>
), you lose type safety.
This means you can add any type of object to the list without the compiler detecting potential type errors. Raw types are discouraged in modern Java programming because they can lead to bugs that are harder to detect at compile time.List<?>
Keep reading with a 7-day free trial
Subscribe to Javarevisited Newsletter to keep reading this post and get 7 days of free access to the full post archives.