Skip to content
标签
欢迎扫码关注公众号

Java Integer 型的比较

两个 Integer 型的值均为 20,结果比较两个值相等时,返回值为 false

根据 java 中 Integer 值比较不注意的问题 中的说法:

Integer 类型对于 -128-127 之间的数是缓冲区取的,所以用等号比较是一致的。

但是值均为 20 时,比较的返回值也是 false

另外再参照了 java 中两个 Integer 类型的值相比较的问题Java 中 Integer 与 int 类型的装箱和拆箱,后者讲的比较详细。


  1. Integer 与 int 类型的赋值
  2. 把 Integer 类型赋值给 int 类型。此时,int 类型变量的值会自动装箱成 Integer 类型,然后赋给 Integer 类型的引用,这里底层就是通过调用 valueOf() 这个方法来实现所谓的装箱的。
  3. 把 int 类型赋值给 Integer 类型。此时,Integer 类型变量的值会自动拆箱成 int 类型,然后赋给 int 类型的变量,这里底层则是通过调用 intValue() 方法来实现所谓的拆箱的。
  4. Integer 与 int 类型的比较
    这里就无所谓是谁与谁比较了,Integer == intint == Integer 的效果是一样的,都会把 Integer 类型变量拆箱成 int 类型,然后进行比较,相等则返回 true,否则返回 false。同样,拆箱调用的还是 intValue() 方法。
  5. Integer 之间的比较
    这个就相对简单了,直接把两个引用的值(即是存储目标数据的那个地址)进行比较就行了,不用再拆箱、装箱什么的。
    值得注意的是:对 Integer 对象,JVM 会自动缓存 -128~127 范围内的值,所以所有在这个范围内的值相等的 Integer 对象都会共用一块内存,而不会开辟多个;超出这个范围内的值对应的 Integer 对象有多少个就开辟多少个内存。
  6. int 之间的比较
    这个也一样,直接把两个变量的值进行比较。

下面是 Integer.valueOf() 的源码:

java
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

可以看出,上面说的 JVM 会自动缓存 -128~127 范围内的值 指的是调用 Integer.valueOf() 方法时的处理。如果有一个是调用 new Integer() 方法赋的值,则变量指向的就不是同一个对象了。

文章开始的两个值为 20 的 Integer 对象之所以不相等,应该是因为都是使用 new Integer() 赋的值。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.