ClassCastException: ArrayList 不能转换为 String [英] ClassCastException: ArrayList cannot be cast to String
问题描述
我收到此错误:
java.lang.ClassCastException: java.util.ArrayList 不能转换为java.lang.String
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String
这是代码:
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;
}
问题出在这一行:
l4.add(re.get(j)+" "+(String)((ArrayList)l.get(i)).get(k));
我尝试将其重写为:
l4.add(re.get(j)+" "+((ArrayList)l.get(i)).get(k));
但是没有用.我该怎么办?
but it didn't work. What should I do ?
推荐答案
你的括号有问题.
您想在 ArrayList
上调用 get(i)
和 get(k)
,然后将其转换为 String
.
You want to call get(i)
and get(k)
on your ArrayList
, then cast that to a String
.
您的代码将 l.get(i)
的结果转换为 String
,然后尝试对其调用 get(k)
.
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;
真正有帮助的一件事是确保列表l
是一个字符串列表列表
.那么你根本不需要投射.您可以通过使用以下声明(如果可能的话)来实现这一点:
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;
}
这篇关于ClassCastException: ArrayList 不能转换为 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!