[Learn JAVA from scratch | Article 25] Generics

Table of contents

Foreword:

Generics:

Additional extensions:

Summarize:


Foreword:

        This article will introduce in detail the generics we have been talking about in JAVA before. Interested students can click to watch.

Generics:

        Generics is a programming concept that allows the use of type parameters when defining a class, interface or method, so that the actual type can be specified at the time of use. By using generics, you can create reusable, type-safe code while increasing your code's flexibility and readability.

        The main purpose of generics is to provide type checking at compile time to ensure type consistency and safety. It allows the same code to be used in different scenarios without writing a separate implementation for each type. Generic code is erased to its non-generic form at runtime, a mechanism known as type erasure.

        In Java, generics use angle brackets (<>) to specify type parameters. For example, you can define a generic class List<E>, where E is a type parameter representing the type of elements in the list. Use List<String> to create a list of string types, and List<Integer> to create a list of integer types. They are both instances of the same generic class, but with different element types.

        Generics can also be used to define methods and interfaces. Using generic parameters in a method allows the method to work with different types of data without having to write a different method for each data type. Generic parameters in an interface can specify a specific type when implementing the interface.

Advantages of generics:
1. Type safety: The compiler can check type errors at compile time to avoid type conversion exceptions at runtime.
2. Code reuse: It is possible to write general-purpose code for different types of data.
3. Readability and maintainability: Generic code is easier to understand and maintain because type information can be specified at definition time.

In fact, the emergence of generics unifies the elements stored in the collection. If generics are not used, when we add elements to the collection, we can add various elements: numbers, strings, etc., but generics standardize the types stored in strings.

Notes on using generics:

1. Generics cannot write basic data types. (explained below)

2. After specifying the basic type of the generic type, when transferring data, you can pass in the class type or its subclass type

2. If you do not write generics, the type defaults to object class (in fact, it is also object class at the end, explained below)

Enter data into a collection without using generics:

import java.util.ArrayList;
import java.util.Iterator;

public class test {
    public static void main(String[] args) {

        ArrayList list=new ArrayList();

        list.add(123);
        list.add("abc");
        list.add(1.2);

        //遍历集合中的每一个元素
        Iterator it = list.iterator();
        while(it.hasNext())
        {
            Object element =  it.next();
            System.out.println(element);
        }
    }
}

operation result:

In the case of not using generics, all data is of type Object. At this time, any type of data can be added to the collection, but the disadvantage is that we cannot call the unique behavior of this type. If we want to force the call, we must use type conversion, and type conversion may bring unexpected errors.

Use generics to input data into collections:

import java.util.ArrayList;
import java.util.Iterator;

public class test {
    public static void main(String[] args) {

        ArrayList<Integer> list=new ArrayList<>();

        list.add(113);
        list.add(125);
        list.add(133);

        //遍历集合中的每一个元素
        Iterator <Integer>it = list.iterator();
        while(it.hasNext())
        {
           int em=it.next();
            System.out.println(em);
        }
    }
}

operation result:

 We can see that after using generics, our input elements can only be of the specified type, and we don’t need the object type to receive the return value of next, just use the int type directly, which means we can directly call this type of method.

Additional extensions:

But in fact, the generics in JAVA are pseudo-generics. 

        Java generics provide the function of type checking at compile time, but type erasure will be performed at runtime, that is, the type information of the generic type is erased to the original type (raw type).

        In Java, generics are a mechanism for performing type checking at compile time. By using generics, you can use type parameters when defining classes, interfaces, and methods, and specify specific types when you use them. This increases the type safety of your code and reduces the possibility of type errors at runtime.

        However, the generic mechanism in Java is actually implemented through type erasure. At compile time, the compiler will check the generic type to ensure the consistency of the type. But in the generated bytecode, the generic type information is erased, and all generic types are replaced with their original types.

Due to the existence of type erasure, there are some restrictions and special cases:
1. Basic types cannot be used as type parameters, only their corresponding wrapper classes can be used. For example, you cannot use the primitive type int, but you need to use Integer.
2. The actual type parameter of the generic cannot be obtained at runtime. For example, there is no way to determine the actual parameterized type of a generic type using the instanceof operator or through reflection.
3. The specific generic type cannot be stored in the collection, only its original type can be stored. For example, you cannot create an ArrayList<int>, only an ArrayList<Integer>.

This mechanism of generic type erasure is called "pseudo-generics" because the type information of generics is not available at runtime. Nevertheless, Java's generic mechanism still provides compile-time type checking, reduces the occurrence of type errors, and improves the readability and maintainability of the code.

In summary, "generics in Java are pseudo-generics" means that Java's generics provide type checking at compile time, but at runtime the type information is erased, leaving only primitive types. Despite some limitations and special cases, generics are a useful programming mechanism.

In fact, these words can be summed up as follows: Although generics specify the type of data when inputting data into the array, when these data are transferred to bytecode, the data type will be erased and become object type. We call this pattern pseudo-generic.

Summarize:

        Generics is a very practical concept. It standardizes the type of data and facilitates our use. Therefore, we must master the concept of generics. We will also explain other applications of generics in detail later.

If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!

Guess you like

Origin blog.csdn.net/fckbb/article/details/131460745