search
HomeJavajavaTutorialDetailed explanation of generics in Java

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 is not the parent class of List. In order to represent various generic parent classes, Java uses "?" to represent generic general Matching. That is, List> represents the parent class of various generic Lists. List generics with this wildcard cannot set (set) elements, but can only obtain (get) elements. Because the program cannot determine the types in the List, it cannot add objects. But the object obtained must be of type Object.

The following methods will cause compilation errors:

List<?> list = new ArrayList<>();
 
list.add(new Object());

A few ideas:

1. List objects cannot be used as List objects, that is to say: The List class is not a subclass of the List class.

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 Not a subtype of 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. The first solution is to change the formal parameter List in the getSize method to List>, but in this case, forced type conversion is required every time the object is obtained, which is more troublesome. Using the wildcard upper limit solves this problem very well. You can change List to List extends Animal>, and the compilation will not be wrong, and no type conversion is required.


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 type is converted to a List, the type check of the collection elements of the List becomes the upper limit of the type variable (that is, Object). This situation is called erasure.

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

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...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

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...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

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...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

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

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

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 default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

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

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

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.