Java:某些情况下的ClassCastException

Java:某些情况下的ClassCastException,java,casting,Java,Casting,我有以下代码: static Object f(Object x) { x = (Integer) 1234; // <- it runs OK (why?) System.out.println(x); return x; } public static void main(String[] args) { HashMap<String, String> before = new HashMap<String, String>(

我有以下代码:

static Object f(Object x) {
    x = (Integer) 1234; // <- it runs OK (why?)
    System.out.println(x);
    return x;
}

public static void main(String[] args) {

    HashMap<String, String> before = new HashMap<String, String>();
    before.put("a", "b");

    HashMap<String, String> after = (HashMap<String,String>) f(before); // <- it fails
    System.out.println(after);
}
为什么从HashMap到Intger的转换运行时没有错误

为什么从HashMap到Integer的转换运行时没有错误

您不能从HashMap强制转换为Integer。您正在将
int
转换为
Integer

1234
是一个
int
文本,当您尝试将其用作引用类型时,它会自动装箱为一个
整数


然后返回该
整数
,并获得一个
ClassCastException
,因为它不能转换为
HashMap

返回1234,然后在此处进行强制转换

这意味着获取一个可以包含任何内容的框的内容,并确保它可以放在一个名为
的框中,该框位于只能包含
HashMap
s的
之后

这不起作用,因为
f(before)
返回的引用不适合该框。因此在运行时出现异常


您可以将您的程序简化为以下内容,以了解发生了什么

Object x = (Integer) Integer.valueOf(1234);               // Unnecessary cast.
HashMap<String, String> m = (HashMap<String, String>) x;  // Fails due to type-unsafe cast.
1。x=(整数)1234;// x=(整数)1234//发生了自动装箱。编译器将原语int转换为整数。
看起来f()总是返回一个整数Objcet。然后尝试将其转换为HashMap。编译器不会抱怨您试图将对象(f()返回值的引用类型)强制转换为HashMap。但是,对象类型是整数,并且在运行时失败

x = (Integer) 1234;
return x;
(HashMap<String,String>) f(before)
HashMap<String, String> after = (HashMap<String, String>) f(before)
Object x = (Integer) Integer.valueOf(1234);               // Unnecessary cast.
HashMap<String, String> m = (HashMap<String, String>) x;  // Fails due to type-unsafe cast.
Integer x = (Integer) Integer.valueOf(1234);
HashMap<String, String> m = (HashMap<String, String>) x;
 Object x = new Integer(0);
 System.out.println((String)x);