How to Convert an ArrayList<Object> to ArrayList<String> in Java?

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

Related Questions

⦿Why Does Comparing Boxed Long Values 127 and 128 Yield Different Results?

Understanding the comparison of boxed Long values in Java and why it fails for values 128 and above.

⦿Does the Order of Insertion Affect Retrieval in an ArrayList?

Learn about the insertion and retrieval order of elements in an ArrayList in Java and how it maintains the sequence.

⦿How to Retrieve Multiple Values from a Spring .properties File as an Array

Learn how to correctly load multiple values from a Spring .properties file into a list using the Spring framework.

⦿What is the Correct Maven Environment Variable: MAVEN_HOME, MVN_HOME, or M2_HOME?

Learn the correct Maven environment variable name among MAVENHOME MVNHOME and M2HOME including their differences and usage.

⦿How to Recreate Database Before Each Test in Spring Boot?

Learn how to ensure your Spring Boot application recreates the database before each test execution. Discover best practices and troubleshoot common issues.

⦿Understanding NullPointerException in Boolean.valueOf() Method

Learn why Boolean.valueOf can throw NullPointerException in Java and how to avoid it with proper code practices.

⦿Should Logger Be Declared as Private Static or Non-Static?

Explore whether to declare a logger as private static or nonstatic including pros cons and best practices for logging in Java.

⦿Understanding the Difference Between a.getClass() and A.class in Java

Explore the nuances between a.getClass and A.class in Java including performance considerations and usage scenarios.

⦿How to Extract a Byte Array from a ByteBuffer in Java?

Learn the best practices for extracting byte arrays from a ByteBuffer in Java including code examples and potential pitfalls.

⦿Why is the `removeRange()` Method in Java's AbstractList Protected?

Explore the rationale behind the protected access modifier of the removeRange method in Javas AbstractList and its implications for developers.

© Copyright 2025 - CodingTechRoom.com