Java wrapper classes and generics

Table of contents

Packaging

Boxing and unboxing

packing

unbox

generic

initial generic


Packaging

The wrapper class is the reference type corresponding to the basic data type, so that the basic data type can also have the ability of object-oriented programming

In java, basic types are not inherited from object. In order to support these basic data types in generic code, java sets a corresponding wrapper class for each basic data type.

Wrapper classes corresponding to basic data types
basic data type Packaging
int Nothing
float Float
double Double
short  Short
long Long
byte Byte
char Character
boolean Boolean

Except for int and char, the others are capitalized

Boxing and unboxing

packing

Convert basic data types to corresponding wrapper classes

Integer a = Integer.valueOf(10);   //装箱操作   把基本数据类型10变为引用数据类型
Integer a1 = 10; //自动转箱 ,帮我们自动完成装箱操作

unbox

Convert the wrapper class to the corresponding basic data type

int b = a.intValue();   //拆箱
double d = a.doubleValue();   //可以根据我们需要的类型选择拆箱后的数据类型
int c = a;  //自动拆箱
double d1 = (double)a;  //可以根据我们需要的类型选择拆箱后的数据类型

The size of Integer needs attention:

When the value is between -128 and 127, it is the value in the array in the Integer wrapper class used

When it exceeds -128 to 127, a new integer object will be new

 

Integer a = 120;
Integer b = 120;
System.out.println(a==b);  //true   

Integer c = 128;
Integer d = 128;
System.out.println(c==d);   //false


generic

Specify a class parameter to parameterize the data type

After the data type is parameterized, let the compiler do the checking

initial generic

class MyArray <E> {  //泛型类

    public Object[] objects = new Object[3];
    public E get(int pos) {
        return (E)objects[pos];
    }
    public void set(int pos,int val) {
        objects[pos] = val;
    }
}

public class test {
    public static void main(String[] args) {
       MyArray<Integer> myArray = new MyArray<Integer>(); //将数据类型参数化
        myArray.set(0,1);
        myArray.set(1,2);
        myArray.set(2,3);
        int integer = myArray.get(1);
        System.out.println(integer);

    }
}

The biggest function is to specify what type of object the current class should hold, and let the compiler check it

When storing data, it can help us automatically perform type checking

When getting elements, it can help us perform type conversion

Guess you like

Origin blog.csdn.net/qq_63525426/article/details/129406651