Question
What is the most efficient way to convert a List<SubClass> to List<BaseClass> in Java without creating a new list?
List<BaseClass> convertedList = new ArrayList<BaseClass>(listOfSubClass);
Answer
In Java, casting a List of subclass instances to a List of base class references is not straightforward due to type safety. This article explains why and offers techniques to minimize overhead while maintaining references to original objects.
// Optimal method using bounded wildcard
public void processList(List<? extends BaseClass> list) {
// Process the list, can reference as BaseClass
for (BaseClass obj : list) {
// Do something with obj
}
}
Causes
- Java's type system prohibits direct casting of collections due to type safety.
- Generics in Java are invariant, meaning List<SubClass> cannot be treated as List<BaseClass> even though SubClass is a subclass of BaseClass.
Solutions
- Use a parameterized method that accepts List<SubClass> and processes it as List<BaseClass>.
- Leverage bounded wildcards such as List<? extends BaseClass> to refer to List<SubClass> as a list of BaseClass without needing to cast.
Common Mistakes
Mistake: Attempting to directly cast List<SubClass> to List<BaseClass> causes compile-time errors.
Solution: Replace direct casting with a wildcard approach, using List<? extends BaseClass>.
Mistake: Creating a new list and copying objects unnecessarily involves performance overhead.
Solution: Utilize bounded wildcards or generics in method parameters to operate on the original list.
Helpers
- convert List to BaseClass
- Java List casting
- List subclass to superclass
- generics in Java
- bounded wildcards Java