首先看一段比较有意思的代码
[java] view plaincopy1.Integer a = 1000,b=1000;
2.Integer c = 100,d=100; public void mRun(final String name){
3. new Runnable() {
4.
5. public void run() {
6. System.out.println(name);
7. }
8. };
9. }
10.
11.
12.System.out.println(a==b);
13.System.out.println(c==d);
如果这道题你能得出正确答案,并能了解其中的原理的话。说明你基础还可以。如果你的答案 是 true 和true的话,你的基础就有所欠缺了。
首先公布下答案, 运行代码,我们会得到 false true。我们知道==比较的是两个对象的引用,这里的abcd都是新建出来的对象,按理说都应该输入false才对。这就是这道题的有趣之处,无论是面试题还是论坛讨论区,这道题的出场率都很高。原理其实很简单,我们去看下Integer.java这个类就了然了。
[java] view plaincopy1.public static Integer valueOf(int i) {
2. return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
3. }
4.
5. /**
6. * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
7. */
8. private static final Integer[] SMALL_VALUES = new Integer[256];
9.
10. static {
11. for (int i = -128; i < 128; i++) {
12. SMALL_VALUES[i + 128] = new Integer(i);
13. }
14. }
当我们声明一个Integer c = 100;的时候。此时会进行自动装箱操作,简单点说,也就是把基本数据类型转换成Integer对象,而转换成Integer对象正是调用的valueOf方法,可以看到,Integer中把-128-127 缓存了下来。官方解释是小的数字使用的频率比较高,所以为了优化性能,把这之间的数缓存了下来。这就是为什么这道题的答案回事false和ture了。当声明的Integer对象的值在-128-127之间的时候,引用的是同一个对象,所以结果是true。
看下面代码
[java] view plaincopy1. Integer a = new Integer(1000);
2.int b = 1000;
3.Integer c = new Integer(10);
4.Integer d = new Integer(10);
5.System.out.println(a == b);
6.System.out.println(c == d);
这道题是继第一题的后续,如果这道题你能很快速的得出答案,那么恭喜你,==比较符你就算掌握的比较透彻了。
------------------------------------------------------分割线-----------------------------------------------------------------------------------------