Summary of generics and wrapper classes in Java

foreword

This blog will give a brief introduction to generics and wrapper classes in Java, and what are the precautions. I will only make my own summary, and make supplementary modifications later with further study.

generic

Concept and Background

Many element types are used in Java, including int wrapper class Integer type, String type and many custom types. When these types want to be used uniformly, there will be type incompatibility. Before 1.5, Java allowed Create an element of type Object, because it is the parent class of all classes, so the parameter can be arbitrarily realized through the reference of type Object. But its disadvantages are also very obvious, because every reference needs to be cast, which requires developers to predict the actual parameter type. If the use is wrong, this exception will be reported at runtime , was criticized. Therefore, after 1.5, the concept of generics was introduced to be used in this scenario.

Java generics is a new feature introduced in J2 SE1.5. Its essence is a parameterized type , that is to say, the type of data operated is specified as a parameter (type parameter). This parameter type can be used in classes, interfaces and In the creation of methods, they are called generic classes, generic interfaces, and generic methods.
The understanding of parameter types in generics can be understood as a placeholder, and then replaced with the specified type when the program is running.

use syntax

class 名称<类型参数列表>{
    
    
}

example

class Test<E>{
    
    
	private E[] arr;
	private size;
	private Test(){
    
    
		arr = (E[])new Object[10];
		
	}

	public static boolean add(E e){
    
    
		arr[size++] = e;
	}

	public static void printArray(){
    
    
		for(E e,arr){
    
    
		System.out.println(e);
	}
}

principle

The essence of generics is to parameterize data types, which is achieved by erasing. The generic .java source code is declared. After the .class file is compiled and generated, the information related to the generic type is erased and replaced with a specific type. This is what the type erasure Java compiler does
in the type erasure phase thing

  • Replace the type variable with the erased type, usually the Object class
  • Add mandatory conversion statements at necessary positions to ensure the safety of the program
  • Add a bridge method to a class that inherits a generic class or a generic interface to preserve polymorphism

Generic types are logically seen as multiple different types, but in fact they are all the same basic type

class T <E> {
    
    
    public void print() {
    
    
        System.out.println("可执行");
    }
}

public class Test5 {
    
    
    public static void main(String[] args) {
    
    
        T<Integer> t1 = new T<>();
        T<String> t2 = new T<>();
        System.out.println(t1.getClass().equals(t2.getClass()));//返回true
    }
}

As can be seen from the above example, when different parameter types are passed in to the same generic class, multiple different types are not really generated. There is only one type, which is the T type. Java generics are only valid during compilation. In , after the incoming parameters are verified to be correct, all the generic information will be erased, so the generic information will not enter the runtime stage.

type boundary

When defining generics, it is necessary to impose certain constraints on the incoming parameter types, which can be achieved by defining its type boundaries

class 名称<类型参数 extends 类型边界>{
    
    
...
}

For example:
insert image description here
for the T generic class defined last time, due to the modification of the type boundary, the E type passed in can only be a subclass of CharSequence, so passing in String is executable, and passing Integer is not executable

wildcard

The above are the categories of generic classes, but what if for a method, the parameters passed in can be of multiple types? Generic wildcards are involved here——?

//语法
public static void function(T<?> t){
    
    
	...
}

Type wildcards generally use ? to replace specific type arguments , and the ? in T<?> Logically, it is the parent class of Integer, String... all defined type arguments

Upper bounds for wildcards:

//语法
T<? extends 上界>

When defining a method, if the parameters passed in can only be subclasses of a certain class, the upper bound of wildcards can be used at this time

public static void function(T<? extends Number> t){
    
    
	...
}
public static void main(String[] args){
    
    
	function(T<Integer> t);
	function(T<Double> t);
	function(T<Long> t);
}

Lower bounds for wildcards:

//语法
T<? super 下界>

Contrary to the upper bound, the lower bound of the wildcard makes the incoming parameters only be the class itself or the parent class

public static void function(T<? super Integer> t){
    
    
	...
}
public static void main(String[] args){
    
    
	function(T<Integer> t);
	function(T<Number> t);
	function(T<Object> t);
}

generic method

grammar

方法限定符 <类型形参列表> 返回值类型 方法名(形参列表){
    
    
...
}
//例
public <E> E fun(T<E> t,int i){
    
    
...
} 
  • To define a generic method, you must add <type parameter list> between the qualifier and the return value to declare that the method is a generic method
  • Only methods declared with <type parameter list> are generic methods, and a method whose formal parameters use generics is not a generic method.
  • Static methods cannot directly access the generics defined on the class. If a static method in a class wants to use generics, the static method must be defined as a generic method, that is, it must be declared through <type parameter list>

limitations

  1. Generic type parameters can only be reference types and not primitive types
  2. Cannot instantiate object of generic type
  3. Cannot use static property of generic type what
  4. Unable to use instanceof to determine the generic type with type parameters
  5. Cannot create array of generic type
  6. Generic classes cannot inherit the Exception class, that is, generic classes cannot be thrown as exceptions
  7. Generic type is not part of formal parameter and cannot be overloaded

Packaging

background and concept

Java is an object-oriented language, and many operations are object-oriented. At this time, its basic types are inconvenient to use. For example, in the generic scenario mentioned above, the input parameter type can only be reference type. Because of this, the Java wrapper class came into being.
The actual wrapper class is to encapsulate the original eight basic data types into various objects for more convenient use.

The packaging classes corresponding to the eight basic data types

insert image description here

Use of wrappers

Take Integer as an example,

  • When converting int to Integer, call the constructor of Integer new Integer(5);
  • When converting Integer to int, call the intValue() method of Integer;
  • Integer also supports converting the string str to Integer, calling the constructor new Integer(str);

Automatically unpack

In Java, if you use == to judge whether a variable a of type int and a variable b of type Integer are equal, it will trigger the automatic unpacking of Integer, that is, variable b will be automatically converted into a variable of type int and compared with it

int a = 10;
Integer b = new Integer(10);
System.out.println(a == b);//返回true

The basic relationship of the wrapper class corresponding to the basic data type

insert image description here
The above is a summary of the knowledge points of generics and packaging classes in Java. With the deepening of follow-up learning, the content will be supplemented and modified synchronously. It will be a great honor to help all bloggers. Please correct me

Guess you like

Origin blog.csdn.net/m0_46233999/article/details/109297807
Recommended