Java 面试题

来源:互联网 发布:java培训机构大全 编辑:程序博客网 时间:2024/04/29 08:00

Java题:为什么128 == 128返回为False,而127 == 127会返回为True?

class A
{
public static void main(String[] args)
{
Integer a = 128, b = 128;
System.out.println(a == b);
Integer c = 127, d = 127;
System.out.println(c == d);
}
}

会得到如下结果:

false
true

如果两个引用指向同一个对像,那么==就成立;反之,如果两个引用指向的不是同一个对象,那么就不成立,即便两个引用的内容是一样的,结果也会出现false.

在Integer.Java类中,有IntegerCache.java这个内部私有类,为-128到127之间的整数对象提供缓存。

而在Integer源码中:

这里写图片描述

如果值在-128到127之间,它就会返回该缓存的实例。

Integer c = 127, d = 127;

两者指向同样的对象。

这就是为什么下面这段代码的结果为true了:

System.out.println(c == d);

继续去看一下 Integer 源码,去深入了解 Integer 缓存机制,下面截个图:

这里写图片描述

根据源码可以发现最后修改 Integer 缓存上限时候的方法有点小瑕疵。我们看看Api给我们怎么建议的一段话:

the size of the cache may be controlled by the {@code -XX:AutoBoxCacheMax=} option.

原来我们只需要:运行时设置 -XX:AutoBoxCacheMax=133 就OK。

8 1
原创粉丝点击