【问题标题】:Why this code compile but crash when run?为什么这段代码编译但运行时崩溃?
【发布时间】:2019-09-24 08:16:28
【问题描述】:

考虑以下代码:

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 永远不会改变。因此,如果进入循环,它将永远不会退出
  • @GBlodgett 不过,这是一个无限循环,而不是崩溃。
  • 测试应该不难......

标签: java compilation crash


【解决方案1】:

首先,您将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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多