ClassCastException: ArrayList cannot be passed to String

I get this error:

java.lang.ClassCastException: java.util.ArrayList cannot be dropped 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?

+4
source share
1 answer

You have a problem with your brackets.

You want to call get(i) and get(k) on an ArrayList , and then pass that String .

Your code passes the result of l.get(i) to String , then tries to call get(k) .

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

The following should work, and also make your code a lot easier:

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

One thing that would really help is to ensure that list l list of string lists . Then you don’t have to quit at all. You can achieve this using the following declaration (if at all possible):

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

Here are some tips on how you could rewrite above and make it a lot easier:

 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; } 
+9
source

All Articles