zoukankan      html  css  js  c++  java
  • Integer 类和 int 基本数据类型的区别

    参考链接学习:https://www.cnblogs.com/yz123/p/11949311.html

    简要:

    1.Integer 类和 int 的区别

      ①、Integer 是 int 包装类,final修饰,int 是八大基本数据类型之一(byte,char,short,int,long,float,double,boolean)

      ②、Integer 是类,默认值为null,int是基本数据类型,默认值为0;

      ③、Integer 表示的是对象,用一个引用指向这个对象,而int是基本数据类型,直接存储数值。

    2.Integer 的自动拆箱和装箱

      自动拆箱和自动装箱是 JDK1.5 以后才有的功能,也就是java当中众多的语法糖之一,它的执行是在编译期,会根据代码的语法,在生成class文件的时候,决定是否进行拆箱和装箱动作。
      ①、自动装箱

      一般我们创建一个类的时候是通过new关键字,比如:

    1 Object obj = new Object();

      但是对于 Integer 类,我们却可以这样:

    1 Integer a = 128;

    为什么可以这样,通过反编译工具,我们可以看到,生成的class文件是:

    1 Integer a = Integer.valueOf(128);

    这就是基本数据类型的自动装箱,128是基本数据类型,然后被解析成Integer类。
      ②、自动拆箱


      我们将 Integer 类表示的数据赋值给基本数据类型int,就执行了自动拆箱。

    1 Integer a = new Integer(128);
    2 int m = a;

      反编译生成的class文件:

    1 Integer a = new Integer(128);
    2 int m = a.intValue();

      简单来讲:自动装箱就是Integer.valueOf(int i);自动拆箱就是 i.intValue();

    3.示例

    public static void main(String[] args) {
        Integer i = 10;
        Integer j = 10;
        System.out.println(i == j);  //true
    
        Integer a = 128;
        Integer b = 128;
        System.out.println(a == b); //false
    
        int k = 10;
        System.out.println(k == i);//true
        int kk = 128;
        System.out.println(kk == a);//true
    
        Integer m = new Integer(10);
        Integer n = new Integer(10);
        System.out.println(m == n); //false
    }

    使用反编译工具Jad,得到的代码如下:

    public static void main(String args[])
    {
        Integer i = Integer.valueOf(10);
        Integer j = Integer.valueOf(10);
        System.out.println(i == j);//true
        Integer a = Integer.valueOf(128);
        Integer b = Integer.valueOf(128);
        System.out.println(a == b);//false
        int k = 10;
        System.out.println(k == i.intValue());//true
        int kk = 128;
        System.out.println(kk == a.intValue());//true
        Integer m = new Integer(10);
        Integer n = new Integer(10);
        System.out.println(m == n);//false
    }
  • 相关阅读:
    vue3配置rem适配
    webPack转vite2
    vite ant Design vue按需加载
    Vue3 +Vite+ts
    vite 2.0 动态引入加载图片
    Vue3使用vmdeditor自定义锚点
    ThinkPHP6 路由
    DIV+CSS 文本属性
    DIV+CSS 入门篇 CSS选择器
    如何不使用react,也能解析jsx?
  • 原文地址:https://www.cnblogs.com/hjh-666/p/15400203.html
Copyright © 2011-2022 走看看