侧边栏壁纸
博主头像
晓果冻博主等级

一个热爱生活的95后精神小伙

  • 累计撰写 120 篇文章
  • 累计创建 14 个标签
  • 累计收到 56 条评论

目 录CONTENT

文章目录

自动拆箱、装箱

晓果冻
2022-04-06 / 0 评论 / 1 点赞 / 42 阅读 / 1,218 字
温馨提示:
本文最后更新于 2022-04-06,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

自动拆箱、装箱

拆箱的情况

  • 调用intValue()
  • 与基本类型做算术运算和==时

装箱情况

  • 直接赋值都会装箱调用valueOf()

    • Integer i =4;
  • 源码

    public class tt {
        public static void main(String[] args) {
            int i = 3;
            int a = 1;
            Integer b = 2;
            Integer c = 3;
            Integer d = 3;
            Integer e = 321;
            Integer f = 321;
            Long g = 3l;
            System.out.println(i == c);
            System.out.println(c == d);
            System.out.println(e == f);
            System.out.println(c == (a + b));
            System.out.println(c.equals(a + b));
           System.out.println(g == (a + b));
            System.out.println(g.equals(a + b));
        }
    }
    
  • 反编译后借用网上老哥的反编译截图
    image-20220406160122573

  • return了一个新对象,IntegerCache.cache数组中的-128-127是在常量池(静态常量池)中的。

        /**
         * Returns an {@code Integer} instance representing the specified
         * {@code int} value.  If a new {@code Integer} instance is not
         * required, this method should generally be used in preference to
         * the constructor {@link #Integer(int)}, as this method is likely
         * to yield significantly better space and time performance by
         * caching frequently requested values.
         *
         * This method will always cache values in the range -128 to 127,
         * inclusive, and may cache other values outside of this range.
         *
         * @param  i an {@code int} value.
         * @return an {@code Integer} instance representing {@code i}.
         * @since  1.5
         */
        public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    
  • 包装类的“==”运算在遇到算术运算的情况下会自动拆箱

    • System.out.println(g == (a + b)); //true
    • 自动拆箱了
      image-20220406172329345
图一运行结果

image-20220406172517761

1

评论区