当前位置:网站首页>为什么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。
边栏推荐
- Classic image segmentation network: UNET supports libtorch deployment reasoning [with code]
- #24class静态成员
- B. Box Fitting-CodeCraft-21 and Codeforces Round #711 (Div. 2)
- [opencv450 samples] read the image path list and maintain the proportional display
- B. Box Fitting-CodeCraft-21 and Codeforces Round #711 (Div. 2)
- CAD中图纸比较功能怎么用
- 社招两年半10个公司28轮面试面经(含字节、拼多多、美团、滴滴......)
- A. Balance the Bits--Codeforces Round #712 (Div. 1)
- C. Fibonacci Words-April Fools Day Contest 2021
- C. Planar Reflections-CodeCraft-21 and Codeforces Round #711 (Div. 2)
猜你喜欢
18亿像素火星全景超高清NASA放出,非常震撼
Uni app -- listen for the exit of the return key
Hibernate architecture introduction and environment construction (very detailed)
毕业旅行 | 伦敦5日游行程推荐
Bi-sql stored procedure (I)
C# IO Stream 流(一)基础概念_基本定义
Style setting when there is a separator in the qcombobox drop-down menu
BI-SQL丨存储过程(一)
QT Chinese and English use different fonts respectively
后序线索二叉树
随机推荐
CSDN force value
Extraction system apk
YUV444、YUV422、YUV420、YUV420P、YUV420SP、YV12、YU12、NV12、NV21
Qt Utf8 与 Unicode 编码的互相转换, Unicode编码输出为格式为 &#xXXXX
go中全类型等值判断解析&综合汇总
CSDN add on page Jump and off page specified paragraph jump
Rk3568+ Hongmeng industrial control board industrial gateway video gateway solution
jdbc常见异常及错误解决办法汇总
The software test interview has been suspended. The interviewer always says that the logical thinking is chaotic. What should I do?
C1. k-LCM (easy version)-Codeforces Round #708 (Div. 2)
213.打家劫舍 II
.user.ini文件导致的php网站安装问题
Go language escape analysis complete record
Uniapp - call payment function: Alipay
录屏转gif的好用小工具ScreenToGif,免费又好用!
C. Yet Another Card Deck-Educational Codeforces Round 107 (Rated for Div. 2)
分享一个OSGeo4W64下载好的库,基于qgis3.10的
18亿像素火星全景超高清NASA放出,非常震撼
Leetcode (435) - no overlapping interval
自定义QComboBox下拉框,右对齐显示,下拉列表滑动操作