Question
How can I convert ArrayList<Object> to ArrayList<String>?
ArrayList<Object> list = new ArrayList<Object>();
list.add(1);
list.add("Java");
list.add(3.14);
System.out.println(list.toString());
Answer
In Java, converting an ArrayList<Object> to an ArrayList<String> requires handling type casting carefully, as you cannot directly cast a list of one type to another. Instead, you need to iterate over the original list, checking each element's type and performing the conversion accordingly.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();
list.add(1);
list.add("Java");
list.add(3.14);
ArrayList<String> list2 = new ArrayList<>();
for (Object obj : list) {
if (obj instanceof String) {
list2.add((String) obj);
}
}
System.out.println(list2.toString()); // Outputs: [Java]
}
}
Causes
- Attempting to directly cast the list using (String)list leads to a compile-time error because Java uses generics and does not allow such casting.
- The original list may contain elements that are not instances of String, leading to ClassCastException at runtime if not handled.
Solutions
- Create a new ArrayList<String> instance.
- Iterate over each element in the original ArrayList<Object> and check if the element is an instance of String using the instanceof operator.
- Cast each valid element to String and add it to the new ArrayList.
Common Mistakes
Mistake: Not checking instance before casting, which results in a runtime error.
Solution: Always use instanceof to check if the object is of the expected type before casting.
Mistake: Trying to cast the entire ArrayList directly, causing a compile-time error.
Solution: Create a new ArrayList and populate it using a loop.
Helpers
- convert ArrayList<Object> to ArrayList<String>
- Java ArrayList conversion
- type casting ArrayList in Java
- ArrayList<Object> example
- Java generics and ArrayList