Java 数组列表
我正在尝试运行我用 Java 编写的程序,但我不知道它发生了什么 给我以下错误:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.util.ArrayList
这是代码:
public static ArrayList connections(ArrayList list3) {
ArrayList connections = new ArrayList();
int row1 = 1;
int row2 = 0;
int col = 0;
connections.add(new ArrayList());
((ArrayList)connections.get(0)).add(0);
((ArrayList)connections.get(0)).add(1);
System.out.print(((ArrayList)connections.get(0)).get(0));
while(row1 < list3.size()) {
if(((ArrayList)list3.get(row1)).get(col).equals(((ArrayList)connections.get(row2)).get(col))){
connections.add(((ArrayList)list3.get(row1)).get(1));
row1++;
}
else {
connections.add(new ArrayList());
connections.add(((ArrayList)list3.get(row1)).get(0));
row2 = row1;
row1++;
}
}
return connections;
}
错误似乎出现在 if 语句中。有人可以帮我解决这个问题吗?
I'm trying to run a program I have made in Java, but I don't know what is happening that it
is giving me the following error:
Exception in thread "main" java.lang.ClassCastException:
java.lang.String cannot be cast to java.util.ArrayList
Here is the code:
public static ArrayList connections(ArrayList list3) {
ArrayList connections = new ArrayList();
int row1 = 1;
int row2 = 0;
int col = 0;
connections.add(new ArrayList());
((ArrayList)connections.get(0)).add(0);
((ArrayList)connections.get(0)).add(1);
System.out.print(((ArrayList)connections.get(0)).get(0));
while(row1 < list3.size()) {
if(((ArrayList)list3.get(row1)).get(col).equals(((ArrayList)connections.get(row2)).get(col))){
connections.add(((ArrayList)list3.get(row1)).get(1));
row1++;
}
else {
connections.add(new ArrayList());
connections.add(((ArrayList)list3.get(row1)).get(0));
row2 = row1;
row1++;
}
}
return connections;
}
It seems that the error is in the if statement. Can somebody help me with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还应该使用泛型而不是强制转换。这样,如果您这样做,您将在编译时收到错误,并且您的代码将是类型安全的。泛型只是向编译器指定您正在使用的类型,以便编译器可以在编译时检查类型。
示例:
有关 泛型的更多信息,请参见此处。
希望这会有所帮助。
You should also use generics instead of casting. That way you will get an error at compile-time if you do this and your code will be type-safe. Generics just specify the type you are using to the compiler so it can check the types at compile-time.
Example:
More about generics here.
Hope this helps.
应该阅读
You arecastingconnections.get(row2) 而不是先转换连接,然后在 arraylist 上执行 get 操作。
编辑——您绝对应该重构代码以使用 Java 1.5 功能(又名泛型)。如果这不是一个选项,您应该重构代码以使其更具可读性 - 例如:您的方法称为“连接”,然后您的变量称为“连接”
should read
You are casting connections.get(row2) instead of casting connections first and then doing a get on the arraylist.
EDIT -- You should definitely refactor the code to use Java 1.5 functionality aka generics. If that's not an option, you should refactor the code to be more readable -- for example : your method is called "connections" and then your variable is called "connections"