djanahana
djanahana

Reputation: 71

ClassCastException: ArrayList cannot be cast to String

I get this error:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String

This is the code:

public static List<String>produit_cart(ArrayList l)
{   
    List<String>re=new ArrayList();
    List<String>l4=new ArrayList();

    re=(List<String>) l.get(0);

    for(int i=1;i<l.size();i++)
    {
        l4=new ArrayList();

        for(int j=0;j<re.size();j++)
        {
            for(int k=0;k<((ArrayList)l.get(i)).size();k++)
            {
                l4.add(re.get(j) +
                        " " +
                        (String)((ArrayList)l.get(i)).get(k));

            }   
        }

        re=new ArrayList();
        for(int m=0;m<l4.size();m++)
        {
            re.add(l4.get(m));
        }   
    }

    return re;
}

The problem is in this line:

l4.add(re.get(j)+" "+(String)((ArrayList)l.get(i)).get(k));

I tried to rewrite it as:

l4.add(re.get(j)+" "+((ArrayList)l.get(i)).get(k));

but it didn't work. What should I do ?

Upvotes: 7

Views: 67487

Answers (1)

jahroy
jahroy

Reputation: 22692

You have a problem with your parentheses.

You want to call get(i) and get(k) on your ArrayList, then cast that to a String.

Your code casts the result of l.get(i) to a String, then tries to call get(k) on it.

... Actually, I can barely determine what your code does, because it is so difficult to read in its current state.

The following should work and also make your code much easier to follow:

ArrayList tempList = (ArrayList) l.get(i);
String tail = (String) tempList.get(k);
l4.add(re.get(j) + " " + tail;

One thing that would really help would be to ensure that list l is a list of string lists. Then you wouldn't have to cast at all. You could achive that by using the following declaration (if at all possible):

List<ArrayList<String>> listL = new ArrayList<ArrayList<String>>();

Here are some suggestions of how you could re-write the above and make it much easier to follow:

public static List<String> produitCart(List<ArrayList<String>> listOfLists)
{   
    List<String> returnList = listOfLists.get(0);

    for (int i = 1; i < listOfLists.size(); i++) {

        List<String> listFour = new ArrayList<String>();

        for (int j = 0; j < returnList.size(); j++) {
            ArrayList<String> tempList = listOfLists.get(i);
            for (int k = 0; k < tempList.size(); k++) {
                listFour.add(returnList.get(j) + " " + tempList.get(k));
            }   
        }

        returnList = new ArrayList();

        for (int m = 0; m < listFour.size(); m++) {
            returnList.add(listFour.get(m));
        }   
    }

    return returnList;
}

Upvotes: 13

Related Questions