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 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]
- The after the type represents a placeholder, indicating that the current class is a generic class ##When instantiating a generic, cannot It is a simple type and needs to be a wrapper class
- Type 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 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
? 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:
extends upper bound>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,- 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:
MyArrayList> 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:
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;//隐式的拆箱
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!

Deployment method of external configuration files of SpringBoot3 project In SpringBoot3 project development, we often need to configure the configuration file application.properties...

Configuration method for converting Apache's .htaccess configuration to Nginx In project development, you often encounter situations where you need to migrate your server from Apache to Nginx. Ap...

JavaWeb application performance optimization: An exploration of the feasibility of Dao-level entity-class caching In JavaWeb application development, performance optimization has always been the focus of developers. Either...

Solving double integrals under polar coordinate system This article will answer a question about double integrals under polar coordinates in detail. The question gives a point area and is incorporated...

How to ensure the uniqueness of script tasks and monitor their operating status in a high concurrency environment? This article will explore how to ensure an outbound foot in a cluster environment...

Regarding how subclasses set private properties by inheriting the setName method of the parent class. In programming, especially in object-oriented programming languages such as Java, subclasses and...

How to solve the problem of username and password authentication failure when connecting to local EMQX using EclipsePaho's MqttAsyncClient? Using Java and Eclipse...

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool