Javase | Wrapper class

1. Packaging

1.1 Packaging

  • 8 types in JavaBasic data types8 more types are prepared accordinglytype of packaging
  • The packaging category belongs toReference data type
  • Six of the packaging classes are packaging classes corresponding to numbers , and their parent classes are allNumber

1.2 Classification of packaging categories

  1. byteThe packaging class corresponding to the type :Byte(The parent class is Number)

  2. shortThe packaging class corresponding to the type :Short(The parent class is Number)

  3. intThe packaging class corresponding to the type :Integer(The parent class is Number)

  4. longThe packaging class corresponding to the type :Long(The parent class is Number)

  5. floatThe packaging class corresponding to the type :Float(The parent class is Number)

  6. doubleThe packaging class corresponding to the type :Double(The parent class is Number)

  7. booleanThe packaging class corresponding to the type :Boolean(The parent class is Number)

  8. charThe packaging class corresponding to the type :Character(The parent class is Number)

( The wrapper class is a reference data type )

2. Thinking: Why provide 8 packaging types?

  • Because 8 basic data types are not enough, 8 packaging types (reference data types) are provided to meet different development needs .

  • The following requirements exist: ( Using wrapper classes can meet the following development requirements ) The parameter type
    in the method is Object o ( reference data type) , but the type of the parameter passed in is 100 ( basic data type ). How to solve this problem? Solution : Encapsulating 100 as a " packaging class " can meet the parameter passing requirements and can also pass in data .

  • Examples include:

    public class IntegetTest01 {
           
           
        public static void main(String[] args) {
           
           
            /*
             现有以下需求:
             调用doSome()方法时传入一个数字100(基本数据类型),但doSome()方法要求传入的参数类			 型为: Object obj(引用数据类型),
             怎么解决这个问题?
    
             解: 可以将数字100经过构造“构造方法”包装成“对象”,把这个"对象"作为参数传入到		     doSome()方法中
             */
    
            //把数字100经过“构造方法”包装成“对象”
            MyInt myInt = new MyInt(100);
            //将“包装类对象”作为参数来传入到doSome()方法中
            doSome(myInt);
    
        }
    
    public static void doSome(Object obj) {
           
            //方法参数为: 一个Object对象
        
              /*
              当没重写toString()方法时,底层默认使用的Object类的toString()方法 : 输出对象		      的“内存地址”信息,返回值为String类型
              如:
               System.out.println(obj); //com.ximo.nine_11.MyInt@7ef20235
    
               建议重写toString()方法
             */
    
            //输出重写了toString()方法的对象 : 输出对象中的数据
            System.out.println(obj);  // 100
        }
    }
    
    
     class MyInt {
           
             //自定义的包装类
        int value;
        public MyInt() {
           
             //无参构造方法
    
        }
        public MyInt(int value) {
           
            //有参构造方法
            this.value = value;
        }
    
         /**
          * Object.toString()方法是Object类下有的方法,Object类是所有对象的父类,
          * 意味着其的子类也能调用toString()方法:
          *
          * Object.toString()方法 : 输出该对象的”内存地址“信息,返回值为String字符串类型 :
          * return getClass().getName() + "@" + Integer.toHexString(hashCode());
          *
          * Object.toString()方法的作用:
          * 1.将“对象”转换为“字符串”
          * 2.返回一个对象的“内存地址”信息,返回值为String类型。
          */
         //重写toString()方法
         @Override
         public String toString() {
           
           
             //返回对象中的数据,返回值类型为String类型
             return String.valueOf(value);
         }
     }
    

3. Obtain the "maximum value" and minimum value by accessing the constants of the packaging class

  • Obtain the " maximum value " and minimum value of the basic data type by accessing the constants of the wrapper class

       //通过访问“包装类的常量”,获取基本数据类型的“最大值”和“最小值”
       System.out.println("byte的最小值: "+Byte.MIN_VALUE); //-128
       System.out.println("byte的最大值: "+Byte.MAX_VALUE); //127
       System.out.println("short的最小值: "+Short.MIN_VALUE); //32768
       System.out.println("short的最大值: "+Short.MAX_VALUE); //32767
       System.out.println("int的最小值: "+Integer.MIN_VALUE); //-2147483648
       System.out.println("int的最大值: "+Integer.MAX_VALUE); //2147483647
       //-9223372036854775808
       System.out.println("long的最小值: "+Long.MIN_VALUE);
       //9223372036854775807
       System.out.println("long的最大值: "+Long.MAX_VALUE);
       System.out.println("float的最小值: "+Float.MIN_VALUE); //1.4E-45
       System.out.println("float的最大值: "+Float.MAX_VALUE); //3.4028235E38
       System.out.println("double的最小值: "+Double.MIN_VALUE); //4.9E-324
       //1.7976931348623157E308
       System.out.println("double的最大值: "+Double.MAX_VALUE);
       System.out.println(Boolean.FALSE); //false
       System.out.println(Boolean.TRUE); //true
       System.out.println(Character.MIN_VALUE);
       System.out.println(Character.MAX_VALUE);
    

4. Packing and unboxing:

4.1 Packing

  • Boxing : Type conversion of " basic data types " to " reference data types ".

  • Boxing : Creating a wrapper class, store the corresponding " basic data type " data into the " packaging class ".

    Examples include:

            /**
              将“基本数据类型”类型转换为 “引用数据类型” (装箱)
              装箱: 创建包装类,将对应的“基本数据类型”数据存储到“包装类”中。
             */
            //基本数据类型
            byte b =12;
            short s =12;
            int i =123;
            long l = 123L;
            float f = 123.0f;
            double d =123.0;
            boolean bl = true;
            char c = '中';
    
        //将“基本数据类型”转换为 “引用数据类型” : 装箱
        //将数字100转换为Byte包装类型 
        Byte B = new Byte(b);             //创建 “byte类型” 对应的包装类:    Byte
        Short S = new Short(s);           //创建 “short类型” 对应的包装类:   Short
    	Integer I = new Integer(i);       //创建 “int类型” 对应的包装类:     Integer
        Long L = new Long(l);             //创建 “long类型” 对应的包装类:    Long
        Float F = new Float(f);           //创建 “float类型” 对应的包装类:   Float
        Double D = new Double(d);         //创建 “double类型” 对应的包装类:  Double
        Boolean BL = new Boolean(bl);     //创建 “boolean类型” 对应的包装类: Boolean
        Character C = new Character(c);   //创建 “char类型” 对应的包装类:    Character
    
            //输出包装类(引用数据类型)对象
            //包装类中重写了toString()方法,所以此处输出包装类中存储的"基本数据类型"数据
            System.out.println(B.toString()); //12
            System.out.println(S.toString()); //12
            System.out.println(I.toString()); //123
            System.out.println(L.toString()); //123
            System.out.println(F.toString()); //123.0
            System.out.println(D.toString()); //123.0
            System.out.println(BL.toString()); //true
            System.out.println(C.toString());  //中
    

4.2 Unboxing

  • Unboxing : Type conversion of " reference data types " to " basic data types ".

  • Unboxing : Call the xxxValue() method in the respective packaging class, outputs the data of the basic data type stored in the wrapper class .

    Examples include:

      //基本数据类型
            byte b =12;
            short s =12;
            int i =123;
            long l = 123L;
            float f = 123.0f;
            double d =123.0;
            boolean bl = true;
            char c = '中';
    
            //装箱
            Byte B = new Byte(b);
            Short S = new Short(s);
            Integer I = new Integer(i);
            Long L = new Long(l);
            Float F = new Float(f);
            Double D = new Double(d);
            Boolean BL = new Boolean(bl);
            Character C = new Character(c);
    
            //拆箱
            /*
              拆箱 : 将"引用数据类型"转换为"基本数据类型"。
              调用各自包装类中有的xxxValue()方法,输出存储在包装类中的基本数据类型的数据。
             */
            byte b_Unpack = B.byteValue();
            Short S_Unpack = S.shortValue();
            Integer I_Unpack = I.intValue();
            Long L_Unpack = L.longValue();
            Float F_Unpack = F.floatValue();
            Double D_Unpack = D.doubleValue();
            Boolean BL_Unpack = BL.booleanValue();
            Character C_Unpack = C.charValue();
    

5.Number class:

5.1 Construction method of Number class

public Number()

5.2 Methods in Number class

  • byte byteValue( ): Returns the specified value
    in byte form .

  • double doubleValue( ): Returns the specified value
    in double form .

  • float floatValue( ): Returns the specified value
    in float form .

  • int intValue( ): Returns the specified value
    in int form .

  • long longValue( ): Returns the specified value
    in long form .

  • short shortValue( )

Returns the specified value in short form .

6.Integer class

6.1 Integer class construction method

  • Two major construction methods of the Integer class :

    Integer( int value )

    Integer( String s )

  • Examples include:

       //Integer的构造方法
       //将数字转换为Integer包装类型(int ---> Integer)
       Integer x = new Integer(100);
       System.out.println(x); //100
    
       //将String类型的数字,转换成Integer包装类型(String ---> Integer)
       Integer y = new Integer("123");
       System.out.println(y); //123
    
  • It is not a number and cannot be packaged into the Integer class . An exception will occur during runtime.

  //以下代码不会报错,是Integer类的构造方法的正确使用范畴
  Integer x = new Integer ("1000");
  Integer y = new Integer (1000);
     System.out.println(x);
  System.out.println(y);

  //这段代码会报错
  //不是一个数字,不能包装成Integer类,运行时会出现异常。
  Integer z = new Integer ("中国");
  System.out.println(z);

6.2 Common methods of Integer class

int intValue( )

  • int intValue( ): Returns the value of this Integer as int type . ( This method is required for unboxing ).

       //装箱
       Integer I = new Integer(123);
    
       //intValue() : 将Integer类型数据以int类型返回
       int i = I.intValue(); //String转换为int
       System.out.println(i); //123
    

int parseInt( String s )

  • int parseInt(String s): Static method , passing in String type parameters, and the return value is int type.

       //静态方法,传入String类型参数,返回值为int类型
       /*
        网页上文本框中输入的实际上是"100"字符串,后台数据库中要求存的是100数字,
        此时java程序要将“100”转换为数字100
        */
       int i  = Integer.parseInt("123");  //将“String类型”数据转换为“int类型”数据
       System.out.println(i);
    
       //该方法不能将中文装换为数字,否则会报“数字格式化异常”
     int i2  = Integer.parseInt("中国"); //报错: NumberFormatException(数字格式化异常)
    
       //照葫芦画瓢 --- 其他的包装类也有类似的方法
       //parseDouble、parseFloat ...
    

String toBinaryString( int i )

  • String toBinaryString( int i): is a static method ,

  • Convert decimal to binary , and the return value is String type.

       //静态的:将十进制转换为二进制,返回值为String类型
       String binaryString = Integer.toBinaryString(3);
       System.out.println(binaryString); // 11
    

String toHexString( int i )

  • String toHexString( int i): is a static method ,

  • Convert decimal to hexadecimal and return value as String type.

       //静态的:将十进制转换为十六进制,返回值为String类型
       String hexString1 = Integer.toHexString(16);
       String hexString2 = Integer.toHexString(17);
       System.out.println(hexString1); //10
       System.out.println(hexString2); //11
    

String toOctalString( int i )

  • String toOctalString( int i ): is a static method ,
  • Convert decimal to octal , and the return value is String type.
   //静态的:将十进制转换为八进制,返回值为String类型
   String octalString = Integer.toOctalString(8);
   System.out.println(octalString); //10

Integer valueOf( int i )

  • Integer valueOf(int i): is a static method ,

  • Convert int type to Integer type

    //静态的:将int类型转换为Integer类型
    Integer i1 = Integer.valueOf(100);System.out.println(i1); //100
    

Integer valueOf( String s )

  • Integer valueOf( String s ): is a static method ,

  • Convert int type to Integer type

       //静态的:将String类型转换为Integer类型
       Integer i2 = Integer.valueOf("100");
       System.out.println(i2); //100
    

7.Construction method of Double class

7.1 Constructor method of Double class

  • Two major construction methods of the Integer class :

    Double( double value)

    Double(String s)

  • Examples include:

       //Double的构造方法
       //将数字转换为Double包装类型 (double ---> Double)
       Double x = new Double(1.23);
       System.out.println(x); //1.23
    
       //将String类型的数字,转换成Double包装类型 (String ---> Integer)
       Double y = new Double("3.14");
       System.out.println(y); //3.14
    

8. Automatic boxing and automatic unboxing:

8.1 Automatic boxing

  • After JDK1.5 , " autoboxing " is supported.

  • autoboxing: Automatically convert basic data type data to wrapper class type (reference data type).

       //自动装箱
       //100基本数据类型
       //int类型数据 - 自动转换为 -> Integer(包装类)
       Integer x = 100; //等于同于: Integer x =new Integer(100);
    

8.2 Automatic unboxing

  • After JDK1.5 , " automatic unboxing " is supported.

  • Automatic unboxing: Automatically convert the wrapper class type (reference data type) into basic data type data.

  • When performing operations such as arithmetic operators and assignment operatorsmeeting"Automatic unboxing".

  • Examples include:

      	    //自动装箱
           Integer x = 1000;
           Integer y = 1000;
    
           Object obj = new Object();
           int a;
    
           /**
             当进行“算术运算符、赋值运算符等”操作时,会”自动拆箱“
    
             算术运算符 : + - * / % ++ - -
             赋值运算符等 : = += -= *= /= %=
            */
           //自动拆箱
           System.out.println(x + 1); 
           System.out.println(x - 1);
           System.out.println(x * 1);
           System.out.println(x / 1);
           System.out.println(x % 1);
           System.out.println(x++);
           System.out.println(x--);
    
           System.out.println(a=x);
           System.out.println(a+=x);
           System.out.println(a-=x);
           System.out.println(a*=x);
           System.out.println(a/=x);
           System.out.println(a%=x);
    
    //会报错,因为“引用数据类型”无法赋值给“基本数据类型” (上面就不会报错,因为会“自动拆箱”)
           System.out.println(a=obj);
    
  • When performing operations such as "== operator"Won't"Automatic unboxing". ( The == operator does not trigger the automatic unboxing mechanism)

    Examples include:

              //自动装箱
             Integer x = 128;
             Integer y = 128;
    
             //进行 ==运算符 操作时,不会自动拆箱
            /*
              当比较基本数据类型时,==比较的是“值”。
              当比较引用数据类型时,==比较的是“内存地址”。
             */
            //两个Integer对象都需要new,内存地址自然是不一样的
            System.out.println(x==y); //false
    
            /**
             *
             * Java中为了提高程序的执行效率,将[-127到128]之间的所有“包装类对象”提前创建好,
             * 放到了一个“方法区”的“整数型常量池”中了,目的是只要用这个区间的数字不需要再去new
             * 对象了,直接从“整数型常量池中”取出来。
             *
             * x变量中保存的对象的内存地址和y变量中的保存的对象的内存地址是一样的。
             * 所以 x==y 为true
             */
            Integer a =127;
            Integer b =127;
            System.out.println(a==b);//true (两个引用都指向同一个对象,内存地址相同)
    
  • With " automatic unboxing ", the method in Number ( unboxing method ) is no longer needed, because manual unboxing is no longer needed .

9.String int Integer type interchange

Insert image description here

       String s1 = "100";

        // String 转换为 int
        int i1 = Integer.parseInt(s1); //100
        System.out.println(i1 + 1); // 101

        // int 转换为 String
        String s2 = i1 + ""; //"101"字符串
        System.out.println(s2 + 1); //字符串拼接: "1011"

        // int 转换为 Integer
        //自动装箱
        Integer x = 1000;

        // Integer 转换为 int
        //自动拆箱
        int y = x;

        // String 转换为 Integer
        Integer k = Integer.valueOf("123");

        // Integer 转换为 String
        String e = String.valueOf(k);

Guess you like

Origin blog.csdn.net/m0_70720417/article/details/132842595