Integer的值为-128~127之间的整数的时候,对象是同一个
观察以下代码:
package com.wanmait.test;
public class Main {
public static void main(String[] args) {
Integer a = 3;
Integer b = 3;
System.out.println(a==b);//true
Integer c = 128;
Integer d = 128;
System.out.println(c==d);//false
}
}Integer的值超过127之后,就不是同一个对象
创建新的对象
Integer a =3;
当值为 int 类型时,会调用 Integer 的静态方法 valueOf()

这是Integer类的valueOf方法。
如果值在-128~127 之间,就从 cache 数组中间取一个对象,所以不会创建新对象
如果不在-128~127 直接,就在堆内存中间 创建新对象

0条评论
点击登录参与评论