考虑以下代码:
public class foo{
static class Node{
Object item;
Node next;
Node(Object item, Node next) {
this.item = item;
this.next = next;
}
}
public static void main(String[] args) {
Node data = null;
data = new Node("hello", data);
data = new Node(5, data);
while (data!=null){
String s = (String) data.item;
System.out.println(s);
}
}
}
这是一个多项选择题,答案是“这段代码将成功编译,但运行时崩溃”。
为什么?
哪里崩溃了?
最佳答案
首先,您正在将 data.item
转换为 String
。这将产生:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
第二,变量数据永远不会在循环内部更新,就像 @GBlodgett 指出的那样。
while (data != null){
String s = (String) data.item;
System.out.println(s);
}
关于java - 为什么这段代码可以编译但运行时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070062/