为什么Integer类型的对象变为基本类型? [重复]

时间:2023-01-16 16:29:58

This question already has an answer here:

这个问题在这里已有答案:

So I have this code:

所以我有这个代码:

public static void main( String[] args )
{
    int i = 3;
    int j = new Integer(5);

    JOptionPane.showMessageDialog(null, Boolean.toString(j.equals(5)));
}

It should open a message dialog with the text "true". The problem is it gives a compiler error saying that I can't invoke a method on the primitive type int. Why is this happening?

它应该打开一个带有文本“true”的消息对话框。问题是它给出了一个编译器错误,说我无法调用基本类型int上的方法。为什么会这样?

Casting ((Integer) j).equals(5) works as expected. I just don't understand why the object j is turning into a primitive type.

Casting((Integer)j).equals(5)按预期工作。我只是不明白为什么对象j变成了原始类型。

1 个解决方案

#1


3  

I just don't understand why the object j is turning into a primitive type.

我只是不明白为什么对象j变成了原始类型。

Because j is not an object in the first place. It is a primitive int. Your new Integer(5) is automatically unboxed on assignment.

因为j首先不是一个对象。这是一个原始的int。您的新整数(5)在分配时自动取消装箱。

#1


3  

I just don't understand why the object j is turning into a primitive type.

我只是不明白为什么对象j变成了原始类型。

Because j is not an object in the first place. It is a primitive int. Your new Integer(5) is automatically unboxed on assignment.

因为j首先不是一个对象。这是一个原始的int。您的新整数(5)在分配时自动取消装箱。