The so-called generics: It allows specifying type parameters when defining classes and interfaces. This type parameter will be determined when declaring variables and creating objects (that is, passing in actual type parameters, which can also be called type arguments)
Generic class or interface
"Diamond" syntax
//定义 public interface List<E> extends Collection<E> public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable //使用 List<String> list = new ArrayList(); //Java7以后可以省略后面尖括号的类型参数 List<String> list = new ArrayList<>();
Deriving a subclass from a generic class
//方式1 public class App extends GenericType<String> //方式2 public class App<T> extends GenericType<T> //方式3 public class App extends GenericType
Pseudo-generic
There is no real generic class. Generic classes are transparent to the Java virtual machine. The JVM does not know the existence of generic classes. In other words, the JVM processes generic classes no differently from ordinary classes. Therefore, type parameters are not allowed in static methods, static initialization blocks, and static variables.
- The following methods are all wrong
private static T data; static{ T f; } public static void func(){ T name = 1; }
The following example can verify from the side that there is no generic class
public static void main(String[] args){ List<String> a1 = new ArrayList<>(); List<Integer> a2 = new ArrayList<>(); System.out.println(a1.getClass() == a2.getClass()); System.out.println(a1.getClass()); System.out.println(a2.getClass()); }
Output
true class java.util.ArrayList class java.util.ArrayList
Type wildcard
First of all, it must be clear that if Foo is the parent class of Bar, but List
The following methods will cause compilation errors:
List<?> list = new ArrayList<>(); list.add(new Object());
A few ideas:
1. List
2. Arrays are different from generics: assuming Foo is a subtype (subclass or subinterface) of Bar, then Foo[] is still a subtype of Bar[]; but G
3. In order to represent the parent class of various generic Lists, we need to use type wildcards. The type wildcard is a question mark (?). Pass a question mark as a type argument to the List collection, writing: List (meaning List of unknown type elements). This question mark (?) is called a wildcard character, and its element type can match any type.
The upper limit of wildcards
List extends SuperType> represents the parent class of all SuperType generic Lists or itself. Generics with wildcard upper limits cannot have set methods, only get methods.
Setting the upper limit of wildcards can solve the following problems: Dog is an Animal subclass, and there is a getSize method to get the number of incoming Lists. The code is as follows
abstract class Animal { public abstract void run(); } class Dog extends Animal { public void run() { System.out.println("Dog run"); } } public class App { public static void getSize(List<Animal> list) { System.out.println(list.size()); } public static void main(String[] args) { List<Dog> list = new ArrayList<>(); getSize(list); // 这里编译报错 } }
The reason for the programming error here is that List is not the parent class of List
Lower limit of wildcard character
List super SubType> represents the lower limit of SubType generic List. Generics with wildcard upper limits cannot have get methods, only set methods.
Generic method
If you define a class or interface without using type parameters, but you want to define the type parameters yourself when defining a method, this is also possible. JDK1.5 also provides generic type method support. The method signature of a generic method has more type parameter declarations than the method signature of an ordinary method. The type parameter declarations are enclosed in angle brackets. Multiple type parameters are separated by commas (,). All type parameter declarations are placed Between the method modifier and the method return value type. The syntax format is as follows:
修饰符 返回值类型 方法名(类形列表){ //方法体 }
Generic methods allow type parameters to be used to express type dependencies between one or more parameters of the method, or method Type dependencies between return values and parameters. If there is no such type dependency, generic methods should not be used. The copy method of Collections uses a generic method:
public static <T> void copy(List<? super T> dest, List<? extends T> src){ ...}
This method requires that the src type must be a subclass of the dest type or itself.
Erase and Convert
In strict generic code, classes with generic declarations should always have type parameters. However, in order to be consistent with old Java code, it is also allowed to use classes with generic declarations without specifying type parameters. If no type parameter is specified for this generic class, the type parameter is called a raw type and defaults to the first upper limit type specified when the parameter is declared.
When an object with generic information is assigned to another variable without generic information, all type information between angle brackets is thrown away. For example, if a List
Example
class Apple<T extends Number> { T size; public Apple() { } public Apple(T size) { this.size = size; } public void setSize(T size) { this.size = size; } public T getSize() { return this.size; } } public class ErasureTest { public static void main(String[] args) { Apple<Integer> a = new Apple<>(6); // ① // a的getSize方法返回Integer对象 Integer as = a.getSize(); // 把a对象赋给Apple变量,丢失尖括号里的类型信息 Apple b = a; // ② // b只知道size的类型是Number Number size1 = b.getSize(); // 下面代码引起编译错误 Integer size2 = b.getSize(); // ③ } }
For more detailed explanations of generics in Java and related articles, please pay attention to the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.