Home  >  Article  >  Java  >  Java generics and wrapper class example analysis

Java generics and wrapper class example analysis

王林
王林forward
2023-04-21 19:19:06705browse

1. What are generics?

The essence of generics is to parameterize types (without creating new types, to control the specific types of parameter restrictions through different types specified by generics) ).

Let’s look at the following example first:

The arrays we learned before can only store elements of specified types. For example: int[] array=new int[10];String[] array=new String[10];The Object class is the parent class of all classes, so can we create an Obj array?

class Myarray{
    public Object[] array=new Object[10];
    public void setVal(int pos,Object val){
        this.array[pos]=val;
    }
    public Object getPos(int pos){
        return this.array[pos];
    }
}
public class TestDemo{
    public static void main(String[] args) {
        Myarray myarray=new Myarray();
        myarray.setVal(1,0);
        myarray.setVal(2,"shduie");//字符串也可以存放
        String ret=(String)myarray.getPos(2);//虽然我们知道它是字符串类型,但是还是要强制类型转换
        System.out.println(ret);
    }
}

After the above code was implemented, we found:

  • Any type of data can be stored

  • No. 2 subscript It is originally a string, but it must be forced to type

to introduce generics. The purpose of generics is to specify what type of object the current container should hold and let the compiler Check it out yourself.

2. Generic syntax

class Generic class name64cf651d6b165900ec3822620c67e863{

//Type parameters can be used here

}

Use of generics:

Generic class5057fde0c218b7ad6f07f575da1a1219 Variable name=new Generic class4b6fb4cd53c3442a4a78c0a706117225(Constructor method actual parameters)

##MyArray list=new MyArraya8093152e673feb7aba1828c43532094();

[Note]

  • The a8093152e673feb7aba1828c43532094 after the type represents a placeholder, indicating that the current class is a generic class

  • ##When instantiating a generic, a8093152e673feb7aba1828c43532094 cannot It is a simple type and needs to be a wrapper class
  • a8093152e673feb7aba1828c43532094Type composition that does not participate in generics
  • cannot new generic types Array
  • Using generics does not require cast type conversion
  • A simple generic:
//此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型
//在实例化泛型类时,必须指定T的具体类型
public class Test<T>{ 
    //key这个成员变量的类型为T,T的类型由外部指定  
   private T key;
 
    public Test(T key) { //泛型构造方法形参key的类型也为T,T的类型由外部指定
        this.key = key;
    }
 
    public T getKey(){ //泛型方法getKey的返回值类型为T,T的类型由外部指定
        return key;
    }
}

Erasure mechanism : The types in a8093152e673feb7aba1828c43532094 will be erased during compilation, so the things in a8093152e673feb7aba1828c43532094 will not participate in the composition of the type. Will erase T as Object.

Why can't an array of a generic type be instantiated?

An important difference between arrays and generics is how they enforce type checking. Arrays store and check type information at runtime, while generics check for type errors at compile time.

The returned Object array may store any type of data, such as string, which is received through an int type array. The compiler considers it unsafe.

3. Upper bound of generics

Syntax:

class generic class nameae04767e494adef5987640e7e50787f7{

}

Example:

public class MyArray{} //E can only be Number or a subclass of Number

public class MyArray587c6b841f9775ac09a42ccb3bfcf6bc>{}

//E must be a class that implements the Comparable interface

[Note] For E that does not specify a boundary, you can see For E extends Object

4, wildcard character

? For use in generics, it is a wildcard. Wildcards are used to solve the problem that anti-generic types cannot be covariant.

The following two pieces of code:

代码一:
public static<T> void printList1(ArrayList<T> list){
   for(T x:list){
      System.out.println(x);
   }
}
 
代码二:
public static<T> void printList2(ArrayList<?> list){
   for(Object x:list){
      System.out.println(x);
   }
}

Wildcards are used in code 2. Compared with code 1, we are not clear about the specific data type passed into code 1 at this time.

(1) Upper bound of wildcard character

Syntax:

a807046160ad0e79be55a1eff6ef7fe7

a2b037db85f4e1df0e812b9647ac55a8 //The actual parameter type that can be passed in is Number or a subclass of Number

Example: For the following relationship, we need to write a method to print a list that stores Animal or Animal subclasses.

Animal
Cat extends Animal

Dog extends Animal

Code 1:
public static <t extends Animal> void print1(List<T> list>{
    for(T animal:list){
        System.out.println(animal);//调用了T的toString
    }
}

At this time the T type is a subclass of Animal or yourself.

Code 2: Implemented through wildcards

public static void print2(List<? extends Animal> list){
    for(Animal animal:list){
       Syatem.out.println(animal);//调用了子类的toString方法
    }
}

The difference between the two codes:

##For methods implemented by generics, 370684dcd157e96b03c92635015a5aca imposes restrictions on T, which can only be a subclass of Animal. Pass in Cat, it’s Cat.
  • For methods implemented by wildcards, it is equivalent to stipulating Animal and allowing subclasses of Animal to be passed in. The specific subcategory is not clear at this time. For example: when Cat is passed in, the declared type is Animal. Only by using polymorphism can the toString method of Cat be called.
  • ## Wildcard upper bound→ Parent-child class relationship:

//You need to use wildcards to determine the parent and child types

MyArrayLista2b037db85f4e1df0e812b9647ac55a8 is the parent class of MyArrayListc0f559cc8d56b43654fcbe4aa9df7b4a or MyArrayListeafb63d086dd6c9bd19609d76bcc2869

MyArrayList6b3d0130bba23ae47fe2b8e8cddf0195 is MyArrayList< ;? extends Number>'s parent class

 ArrayList<Integer> arrayList1 = new ArrayList<>();
 ArrayList<Double> arrayList2 = new ArrayList<>();
 List<? extends Number> list = arrayList1;
 //list.add(1,1);//报错,此时list的引用的子类对象有很多,再添加的时候,任何子类型都可以,为了安全,java不让这样进行添加操作。
 Number a = list.get(0);//可以通过
 Integer i = list.get(0);//编译错误,只能确定是Number子类

[Note]

cannot be added to it. What is stored in the list may be Number or Number A subclass of which the type cannot be determined.

  • The wildcard upper bound is suitable for reading but not for writing.

  • (2) Lower bound of wildcard

  • Syntax:

fab79a2d6e2f2507f662992b205ae3ba

6a4551997e2af77c2331ddf9cfbb1e38//The parameter type that can be passed in is Integer or the parent class of Integer

The parent-child class relationship of the wildcard lower bound:

MyArrayList474555482eb79f9e4e676a9012437c1d是MyArrayList1c0477c859e3a4cbd4faa63087d62a35的父类类型

MyArrayLista10469e4b40f04339ce5bebfbf5abb4c是MyArrayList474555482eb79f9e4e676a9012437c1d的父类

通配符下界适合写入元素,不适合读取。

5、包装类

在Java中,由于基本类型不是继承自Object,为了在泛型中可以支持基本类型,每个基本类型都对应了一个包装类。除了Integer和Character,其余基本类型的包装类都是首字母大写。

拆箱和装箱:

int i=10;
 
//装箱操作,新建一个Integer类型对象,将i的值放入对象的某个属性中
Integer ii=i;  //自动装箱
//Integer ii=Integer.valueOf(i);
Integer ij= new Integer(i);//显示装箱
 
//拆箱操作,将Integer对象中的值取出,放到一个基本数据类型中
int j=ii.intValue();//显示的拆箱
int jj=ii;//隐式的拆箱

The above is the detailed content of Java generics and wrapper class example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete