HoneyMoose
  • 首页
  • Java
  • Jersey
  • Jira
  • Confluence
  • U.S.
    • USRealEstate
    • USVisaTrack
    • H1B
  • 项目和网站
    • CWIKI.US
    • OSSEZ 社区
    • WIKI.OSSEZ.COM
    • BUG.OSSEZ.COM
    • RSS.OSSEZ.COM
BLOG.OSSEZ.COM
A responsive blog theme focused om user reading experience
  1. Home
  2. Computer Science
  3. This article

Java 有关 Integer 一个好玩的包装类

2022年05月01日 481Browse 0Like 0Comments

废话不多说,看看下面的代码。

        Integer i1 = 100;
        Integer i2 = 100;
        Integer i3 = 200;
        Integer i4 = 200;

        System.out.println(i1 == i2);
        System.out.println(i3 == i4);

你可以猜猜上面的代码输出的是什么吗?

解答

上面代码输出的是 ture 和 false

首先需要知道,Java 在对象中使用 == 比较的是地址,不是值。

因为我们使用类包装类,那么有关 int 的包装类肯定在这里有一个诡异的地方,这个诡异的地方就在于:

在通过 valueOf 方法创建 Integer 对象的时候,如果数值在 [-128,127] 之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象。

 

integer-w-c-01

 

下面的代码就是 Int 的有关 valueOf

 

integer-w-c-02

 

关于英文的说明就是:

as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

为了更好的空间和时间性能,对在 -128 到 127 之间的整数进行缓存了,对这个这个区间之外的变量也有可能进行了缓存。

因此上面的代码就会得到上面的结果。

有相同情况的还包括有 Long,我们看了下 Double 和 Float 这 2 个对象,Java 并没有对这 2 个对象进行缓存。

https://www.ossez.com/t/java-integer/13782

Tags: None
Last updated:2022年05月01日

Kratos

stay absorbed stay excellent

Like
< Previous
Next >

Comments

Cancel reply

Newest Hotspots Random
Newest Hotspots Random
IntelliJ IDEA 2023.1 版本添加了包中类的列表功能 Jenkins 修改启动的端口 Spring 项目运行提示错误 Not a managed type Linux 查看 SELinux 的状态 WordPress 网站 Error Establishing a Database Connection(建立数据库连接时出错) Linux 开启或关闭 SELinux
如何从 Java 的 List 中删除第一个元素 安装 Spring Boot CLI 湘南古村 —— 塘付村(地理位置) Confluence 6 快捷键 Java 线程安全 Thread-Safety 2021 疫情期间美国公司技术岗的面试流程
Categories
  • Algorithm(算法)
  • AMQP
  • Angular
  • CI
  • Compile And CI
  • Computer Science
  • Confluence
  • DataBase
  • Gradle
  • H1B
  • Hibernate
  • IDE
  • Java
  • Jersey
  • Jira
  • MariaDB
  • PrestaShop
  • Spring
  • Spring Batch
  • U.S.
  • USRealEstate
  • USVisaTrack
  • 我的小厨

COPYRIGHT © 2020 HoneyMoose. ALL RIGHTS RESERVED.

THEME CWIKIUS.CN MADE BY VTROIS