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.
class Generic class name
{ //Type parameters can be used here
}
Use of generics:
Generic class
Variable name=new Generic class (Constructor method actual parameters)
##MyArray list=new MyArray<>();[Note]
//此处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 <> will be erased during compilation, so the things in <> 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:public class MyArray{} //E can only be Number or a subclass of Numberclass generic class name
{ }
Example:
public class MyArray
//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
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
Animalextends Number> //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.
Cat extends AnimalDog 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,## Wildcard upper bound→ Parent-child class relationship:
MyArrayList> is MyArrayList< ;? extends Number>'s parent class
[Note]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子类Copy after login
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
The parent-child class relationship of the wildcard lower bound:MyArrayList super Integer>是MyArrayList
的父类类型 MyArrayList<?>是MyArrayList super Integer>的父类
通配符下界适合写入元素,不适合读取。
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;//隐式的拆箱Copy after loginThe 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!