整数与int比较 [英] Integer vs. int comparison

查看:114
本文介绍了整数与int比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 java 的新手。我现在正在学习 java 中的非原始Integer类型。
我知道以下比较无效并引发编译错误 -

I am new to java. I am now learning the non-primitive Integer type in java. I know the following comparison is not valid and throws a compilation error -

String str = "c";
Char chr = 'c';
if(str == chr) return true;

上面的代码片段给了我 - Test.java:lineNumber:无与伦比的类型:java.lang .String和char错误。

The above code snippet gives me the - "Test.java:lineNumber: incomparable types: java.lang.String and char" errors.

但我发现下面的代码片段编译得很好 -

But I found the following code snippet compiles fine -

int a = 1234;
Integer aI = 1234;
if(a==aI) return true; 

这里, a 是原始的int和 aI 是非原始的。那么它们如何可比?我是编程的新手,可能是我不知道的任何事情。

Here, a is primitive int and aI is non-primitive. So how they are comparable? I am new to programming, may be is there any thing I don't know.

谢谢

推荐答案

这称为拆箱。这里aI是非原始/引用类型。这里Integer是原始int的包装器。它为原始int提供了一些易于使用的操作。例如,每个基本类型( boolean,byte,char,short,int,long,float,double )都有相应的包装类型(布尔,字节,字符,短,整数,长, Float,Double )。

This is called unboxing. Here aI is non-primitive/reference type. Here Integer is an wrapper of primitive int. Its gives some extra easy to use manipulations over primitive int. Each primitive type for example (boolean, byte, char, short, int, long, float, double) has a corresponding wrapper type (Boolean, Byte, Character, Short, Integer, Long, Float, Double).

所以当 a aI进行比较时,首先 aI 未装箱并成为原始int,并将其值与原始int进行比较。这意味着它相当于 -

So when a is compared with aI, first aI is unboxed and become a primitive int and it's value is compared with the primitive int. That means it is equivalent to -

int a = 1234;
Integer aI = 1234;
int a2 = aI.intValue();
if(a == a2) return true;

对于第一次比较,比较发生在两种不同的数据类型之间 - String char 。在这种情况下,在java中没有定义将 char 转换为 String String <的规则/ code>默认情况下 char

And for the first comparison the comparison occurred between completely two different data types - String and char. In this case there is no rule defined in java to convert char to String or String to char by default.

这篇关于整数与int比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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