java 自动拆箱的陷阱
来源:互联网 发布:阿里经典java面试题 编辑:程序博客网 时间:2024/05/04 04:55
java 自动拆箱运用非常广泛。但是这里面有一些“陷阱”。废话不多说,来看一段代码:
public static void main(String[] args) {Integer a=1;Integer b=2;Integer c=3;Integer d=3;System.out.println(c==(a+b));System.out.println(c==d);System.out.println(c.equals(d));Integer f=200;Integer e=200;System.out.println(e==f);System.out.println(e.equals(f));}
打印结果:
true
true
true
false
true
如果说以上的运算都进行自动拆箱那打印的结果应该都是true。在这里先说明一下== 符号并不会发生自动拆箱,所以也就出现了以上的问题。但是仔细观察一下,就有人会说,那不是明明c==d吗?为了解开谜团,我们必须要了解这个装箱过程。我们来看一下对以上代码的反汇编结果:从以上的代码片段可以发现,原来是调用了Integer.valueOf这个类方法。我们来看一下这个类方法:
/** * Returns a {@code Integer} instance for the specified integer value. * <p> * If it is not necessary to get a new {@code Integer} instance, it is * recommended to use this method instead of the constructor, since it * maintains a cache of instances which may result in better performance. * * @param i * the integer value to store in the instance. * @return a {@code Integer} instance containing {@code i}. * @since 1.5 */ 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];
看到以上的代码,我相信清楚了为什么会发生以上的结果了。因为缓存了[-128,127] 。
1 0
- java 自动拆箱的陷阱
- Java自动装箱和自动拆箱的陷阱
- java中自动装箱拆箱的陷阱
- Java的自动装箱陷阱
- Java自动装箱的陷阱
- Integer的自动拆箱装箱陷阱
- java 自动装箱与拆箱 中的陷阱
- java 自动装箱与拆箱 中的陷阱
- Java自动装箱与拆箱及其陷阱
- Java自动装箱与拆箱及其陷阱
- Java自动装箱与拆箱及其陷阱
- Java自动装箱与拆箱及其陷阱
- java自动装箱陷阱
- Integer的自动拆装箱的陷阱
- Integer的自动拆装箱的陷阱
- 自动装箱与拆箱中的陷阱
- JAVA语法糖之自动装箱的陷阱
- [jjzhu学java]之自动装箱的陷阱
- 用 Spring Security 4+Spring MVC+Spring4 构建健壮且安全的web应用
- Reverse Nodes in k-Group
- java编程的一些建议
- oracle11g服务的打开、关闭的BAT
- Android Activity的探讨——入门
- java 自动拆箱的陷阱
- 怎样从ipa格式文件获取资源图片
- 【POJ2063】【Investment】
- How PowerShell Differs From the Windows Command Prompt
- Java Metrics
- 小贝_redis key键值学习
- 安装VC++后,打开“计算机”很慢
- 红外发射与调制信号
- java基础常见面试题