等于运算符如何处理原始和对象类型数据 [英] how equal operator works with primitive and object type data

查看:144
本文介绍了等于运算符如何处理原始和对象类型数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个非常基本的问题,但我想清楚这个概念。我想知道 == 运算符如何在原始和对象类型的情况下工作。例如

I know its a very basic question but I want to be clear about the concept. I want to know how == operator works in case of primitive and object type. For example

Integer a = 1;
int b = 1;
System.out.println(a == b)

如何 a b 进行比较,而 a 包含包含值的对象的ref有人可以向我说清楚它是如何在内部运作的吗?

how a is compared with b, whereas a contain the ref of object that contains value 1. Can somebody clearify it to me how it works internally?

推荐答案

通常,Java中的等于运算符执行所谓的浅层比较。换句话说,它比较变量包含的值。现在,原始数据类型的变量包含值本身,而引用类型包含对存储实际内容的堆区域的引用。这意味着在您的代码段 int b 将保存值 1 整数a 将保存堆上实际Integer对象的内存地址。

In general the equality operator in Java performs a so called shallow comparison. In other words it compares the values that variables contains. Now the variables of primitive data types contains the value itself while the reference types contains reference to heap area which stores the actual content. That means that in your code snippet int b will hold value 1 and Integer a will hold the memory address of the actual Integer object on the heap.

现在,在您提供的特定示例中,有一个特征。 Integer类是一个包装原始整数类型的特殊包装类。编译器可以自动在这些包装器对象和基本类型(称为装箱和拆箱)之间进行转换。

Now in the particular example provided by you there is one pecularity. Integer class a special wrapper class that wraps primitive integer types. The compiler can automatically convert between such wrapper objects and primitive types (which is called boxing and unboxing).

让我们一步一步地告诉您代码清楚。

Let's walk you code step by step tgo make it clear.

Integer a = 1;

编译器实际上替换了此行中的以下代码:

The compiler actually substitue the following code insted of this line:

Integer a = Integer.valueOf(1);

静态方法 valueOf 返回一个包装器对象包装提供的原始值的实例。当编译器从基本类型构造包装类时,此过程称为装箱。

The static method valueOf returns an wrapper object instance that wraps the provided primitive value. This procedure when the compiler constructs a wrapper class out of a primitive type is called boxing.

使用此类包装器对象时,使用相等运算符将其与基元变量进行比较

When using such a wrapper object is compared with with a primitive variable using equality operator

a == b

编译器实际上将其更改为以下内容:

the compiler actually changes it to the following:

a.intValue() == b;

其中 intValue 返回包含的原始值包装器对象(称为拆箱),即它将原始值解包并使表达式等效于比较两个基元。这就是为什么等于运算符然后返回 true

where intValue returns the primitive value wrapped by the wrapper object (which is called unboxing) i.e. it unboxes the primitive value and make the expression equivalent to comparing two primitives. This is why the equality operator then returned true

这篇关于等于运算符如何处理原始和对象类型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆