Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ClassCastException when taking element from the ArrayList

I have an ArrayList and when I’m trying to access some objects I get ClassCastException: class java.lang.Double cannot be cast to class java.lang.String. But ArrayList only has Strings in it…

Here’s the fragment of the code.

    ArrayList<ArrayList<String>> listDefect = getListSortingDefectWithoutMTPGrouping(party1, party2);
 
    for (int i = 0; i < listDefect.size(); i++) {
            ArrayList<String> list = listDefect.get(i);
            <...>
            cell.setCellValue(list.get(2));

getClass() returns String for this element, and if I’m trying to print it with System.out.println I’m getting the same exception, but the element is still being printed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to play dirty and erased the type from the List.

 for (int i = 0; i < listDefect.size(); i++) {
        ArrayList list = listDefect.get(i);
        <...>
        cell.setCellValue(list.get(2));

It didn’t help.

The method I’m calling to collect data also returns only Strings and throws no exceptions.

private ArrayList<ArrayList<String>> getListSortingDefectWithoutMTPGrouping(String party1, String party2) 

I don’t know what can be the problem, can anyone help?

>Solution :

I think you should check how your ArrayLists inside listDefect are populated. It is definitely possible in Java to have a List<String> that contains Double values instead of Strings by doing a few casts. Check out this piece of code:

import java.util.List;

public class MyClass {
    public static void main(String args[]) {
        
        Double d = 10.0D;
        var l = List.of(d);
        List<?> l1 = (List<?>)l;
        List<String> l2 = (List<String>)l1;

        String foo = l2.get(0);
    }
}

It runs completely fine until you try to assign l2.get(0) to a String variable. If you try to do so, it will throw

Exception in thread "main" java.lang.ClassCastException: class java.lang.Double cannot be cast to class java.lang.String (java.lang.Double and java.lang.String are in module java.base of loader 'bootstrap')
    at MyClass.main(MyClass.java:11)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading