java - 为什么这段代码可以编译但运行时崩溃?

标签 java compilation crash

考虑以下代码:

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/

相关文章:

java - 编译隔离的java文件

compilation - 使用 Clang 编译 RISC-V

android - 调试 Android 应用程序崩溃 - logcat 中没有信息,附加时控制台中没有信息

32 位和 64 位 JRE 上的 SWT

java - 如何从具有多个模块的项目中获取正确的 list ? [JAVA]

C++——返回模板类型 vector 的函数

android - 按下按钮时我的第一个应用程序崩溃

java - “发生Java异常” Apache POI错误

java - 将输出分成 4 张椅子和蛮力方法的 block

java - Android 首选项不起作用