一、==符的使
首先看一段比较有意思的代码
Integer a = 1000,b=1000;
Integer c = 100,d=100; public void mRun(final String name){ new Runnable() { public void run() { System.out.println(name); } }; }
System.out.println(a==b);
System.out.println(c==d);
如果这道题你能得出正确答案,并能了解其中的原理的话。说明你基础还可以。如果你的答案 是 true 和true的话,你的基础就有所欠缺了。
首先公布下答案, 运行代码,我们会得到 false true。我们知道==比较的是两个对象的引用,这里的abcd都是新建出来的对象,按理说都应该输入false才对。这就是这道题的有趣之处,无论java语言基础练习题是面试题还是论坛讨论区,这道题的出场率都很高。原理其实很简单,我们去看下Integer.java这个类就了然了。
如果你想学习java可以来这个群,首先是一二六,中间是五三四,最后是五一九,里面有大量的谢谢资料可以下载。
public static Integer valueOf(int i) { return i >= 128 || i < -128 new Integer(i) : SMALL_VALUES[i + 128]; } /* A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing */ private static final Integer[] SMALL_VALUES = new Integer[256]; static { for (int i = -128; i < 128; i++) { SMALL_VALUES[i + 128] = new Integer(i); } }
当我们声明一个Integer c = 100;的时候。此时会进行自动装箱操作,简单点说,也就是把基本数据类型转换成Integer对象,而转换成Integer对象正是调用的valueOf方法,可以看到,Integer中把-128-127 缓存了下来。官方解释是小的数字使用的频率比较高,所以为了优化性能,把这之间的数缓存了下来。这就是为什么这道题的答案回事false和ture了。当声明的Integer对象的值在-128-127之间的时候,引用的是同一个对象,所以结果是true。
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/h6javajc/26170.html