当前位置:网站首页>What is a generic? Why use generics? How do I use generics? What about packaging?

What is a generic? Why use generics? How do I use generics? What about packaging?

2022-06-11 16:13:00 Java ape~

Catalog

Why generics

️ Know generics

️ Why do we need packing

️ Packaging

️ The basic type corresponds to the packaging class

️ Packing and unpacking

Automatic packing and unpacking

Classic interview questions


Why generics

Let's first implement a simple version with an array MyArrar, Inside the store int Element of type

public class MyArray {
    int[] array;
    int size;  // Number of valid elements in the array 
    
    public MyArray(int initCapacity){
        if(initCapacity <= 0){
            initCapacity = 10;
        }
        array = new int[initCapacity];
    }
    
    // Tail insertion 
    public void add(int e){
        if(size >= array.length){
            System.out.println("MyArray It's full ");
            return;
        }
        array[size] = e;
        size++;
    }
    
    // obtain index Elements in position 
    public int get(int index){
        if(index<0 || index>=size){
            throw new ArrayIndexOutOfBoundsException(" Array subscript out of bounds ");
        }
        return array[index];
    }

    public static void main(String[] args) {
        MyArray myArray = new MyArray(5);
        myArray.add(1);
        myArray.add(2);
    }
}

But we Don't want to In the MyArray in add to int type The elements of , What would ?

Creating a class ? It does not reflect the reusability of the code , too trouble

Use Object type Come on receive data ? Sure  , Let's create MyArray, Creating a Student And a class Person class , And add some data , See what problems will be revealed when using ?

class Person{
    int age;
    String name;
}
class Student{
    String name;
    int age;
}
public class MyArray {
    Object[] array;
    int size;

    public MyArray(int initCapacity){
        if(initCapacity <= 0){
            initCapacity = 10;
        }
        array = new Object[initCapacity];
    }

    public void add(Object e){
        if(size >= array.length){
            System.out.println("MyArray It's full ");
            return;
        }
        array[size] = e;
        size++;
    }

    public Object get(int index){
        if(index<0 || index>=size){
            throw new ArrayIndexOutOfBoundsException(" Array subscript out of bounds ");
        }
        return array[index];
    }
    
    public static void main(String[] args) {
        MyArray myArray = new MyArray(10);
        myArray.add(new Person());
        myArray.add(new Person());
        myArray.add(new Student());
        myArray.add(new Student());
    }
}

I want to get one Person object

If you find out, you will report an error , Think about why ?

because MyArray Deposit is Object,Object Is the parent of all classes , So here There is a downward transformation , The downward transformation is unsafe Of , So we have to turn around

At this time, the problem is solved

But there is another problem at this time :

Observe , It was found that Person type , Why Student Type reception , The compiler does not report errors ?

We can run it to see how it turns out :

ClassCastException by Type conversion exception , It's a kind of Runtime error , So in No errors will be reported during compilation , Will complete the compilation , But an error will be reported at runtime

Why this kind of mistake ?

because MyArray We usually don't know what kind of things are stored in it , So when receiving , Unable to select the correct type to receive , So it will lead to this kind of error

So for the above question , Use Object type To receive can be achieved , but Not an option , Because there will be Move down , And the class Type conversion error , It makes us write very trouble

This is the time , Generics appear , Use Generic Can solve the above problems very well

️ Know generics

Generics refer to type parameterization , That is, set the type to a specific format parameter when writing code , This parameter can specify different types to control the type of formal parameter specific restrictions

️‍️ Use generics to modify the above code to realize the usage of generics

public class MyArray<T> {
    T[] array;
    int size;

    public MyArray(int initCapacity){
        if(initCapacity <= 0){
            initCapacity = 10;
        }
        array = (T[])new Object[initCapacity];
    }

    public void add(T e){
        if(size >= array.length){
            System.out.println("MyArray It's full ");
            return;
        }
        array[size] = e;
        size++;
    }

    public T get(int index){
        if(index<0 || index>=size){
            throw new ArrayIndexOutOfBoundsException(" Array subscript out of bounds ");
        }
        return array[index];
    }
}

Here's a problem :

stay new When the object , Generic types must be replaced with concrete types , Use here Object And in the forced conversion

Insert... Into the inside Person and Student object

        MyArray<Student> myArray1 = new MyArray<>(10);
        myArray1.add(new Student());
        MyArray<Person> myArray2 = new MyArray<>(10);
        myArray2.add(new Person());

When the generic parameter is specified as Student Type , If you're inserting Person Object ? 

The compiler directly reports an error , Once the description type is determined , You can't insert other types of objects into it  

Be careful :

Generic yes Function during compilation A mechanism of

🥎 Generic In the code The run-time between , Will be carried out in Type Erasure , The bottom layer actually uses Object Realization Of , But the user doesn't have to force the type change in the code , Let the compiler check at compile time

Check bytecode :

️ Why do we need packing

If we want to go MyArray Insert int The type of data ?

Found replacing generic parameters with int Will report a mistake , The reason is that only reference types can replace generic parameters , and int For the basic type , What to do at this time ?

The wrapper class corresponding to the basic type solves this problem  

️ Packaging

️ The basic type corresponds to the packaging class

Basic data type Packaging
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

️ We only remember Integer and Character, Because everything else is Basic type initial caps

️ Packing and unpacking

Packing : Is to convert the basic type to the corresponding packaging type

        int i = 10;
        Integer in1 = Integer.valueOf(i);
        Integer in2 = new Integer(i);

Unpacking : Is to convert the package type to the corresponding basic type  

        Integer in3 = new Integer(10);
        int a = in3.intValue();

Automatic packing and unpacking

It can be seen from the above packing and unpacking operations , Packing and unpacking increase the amount of tedious code for us , So in order to reduce the burden of development ,Java It provides automatic packing and unpacking mechanism

        int n = 10;
        
        Integer in6 = n; // Automatic boxing 
        
        int m = in6; // Automatic dismantling 

Classic interview questions

See what the following code will output ?

public class test2 {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;

        Integer c = 128;
        Integer d = 128;

        System.out.println(a==b);
        System.out.println(c==d);
    }
}

Why is that ?

️‍️ to glance at Integer Bottom source :

 

Find out Integer The bottom layer maintains an array , The range of this array value is [-128,127], If Integet The value of the object is in this range , Directly from cache Take in array , Similar to string constant pool , Namely Integer The reference of type directly points to the address of the corresponding value of the array , If Integer The value of the object exceeds this range , New objects will be created

Simple summary :[-128,127],Integer Direct comparison value , Beyond this range, new objects will be created

Look at the question above :

原网站

版权声明
本文为[Java ape~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111554561497.html