当前位置:网站首页>为什么Integer的比较最好使用equals
为什么Integer的比较最好使用equals
2022-06-25 22:03:00 【白衣若尘】
为什么Integer的比较建议使用equals呢?难得“==”不香吗
1. int与int的比较
int作为8种基础类型之一,值是分配在栈上的。而且基础类型没提供equals方式,只能用“==”。
2. Integer与int的比较
Integer对象分配在堆,比较的时候需要用equals吗?并不需要,“==”依然是真香的。
因为“Integer ==int” 是等同于 Integer.intValue() ==int 的。
public static void main(String[] args) {
System.out.println("5==5: " + test(5,5));
System.out.println("127==127: " + test(127,127));
System.out.println("128==128: " + test(128,128));
}
static boolean test(Integer num1, int num2){
return num1 == num2;
}

3. Integer与Integer的比较
static boolean test(Integer num1, Integer num2){
return num1 == num2;
}

可以看到5和127的比较,“==”依然是真香的。 实际-128到127在Integer.IntegerCache的数组中有做缓存,所以这个范围内的所有Integer的对象都是同一个,即引用地址相同。
4. 结论
Integer与Integer的比较最好使用equals,毕竟不知道什么时候,Integer的值会不在那个范围。
那是不是可以用int不用Integer呢?也是不行的,int默认初始化值位0,Integer为null。
边栏推荐
猜你喜欢

Rk3568+ Hongmeng industrial control board industrial gateway video gateway solution

What is Unified Extensible Firmware Interface (UEFI)?

Visual studio code create minimal web API (asp.net core)

实例:用C#.NET手把手教你做微信公众号开发(21)--使用微信支付线上收款:H5方式

YUV444、YUV422、YUV420、YUV420P、YUV420SP、YV12、YU12、NV12、NV21

ACM. Hj16 shopping list ●●

Kylin

后序线索二叉树

Reprint: detailed explanation of qtablewidget (style, right-click menu, header collapse, multiple selection, etc.)

字符串
随机推荐
C2. k-LCM (hard version)-Codeforces Round #708 (Div. 2)
The package name of the manifest file in the library project and the app project are not the same
C. Fibonacci Words-April Fools Day Contest 2021
Solve 'tuple' object has no attribute 'lower‘
字符串
先序线索二叉树
hiberate架构介绍及环境搭建(非常详细)
213.打家劫舍 II
C. Yet Another Card Deck-Educational Codeforces Round 107 (Rated for Div. 2)
QComboBox下拉菜单中有分隔符Separator时的样式设置
Qt自定义实现的日历控件
util. Collection and encapsulation of JS tool functions
#23class介绍
Record the ideas and precautions for QT to output a small number of pictures to mp4
proxy
mysql集群
后序线索二叉树
B. Box Fitting-CodeCraft-21 and Codeforces Round #711 (Div. 2)
Download the latest V80 version of Google Chrome
Spark日志分析