Home Java javaTutorial A closer look at generics in Java

A closer look at generics in Java

Jul 18, 2017 am 09:47 AM
java Base

         Definition of generics: Generics are a new feature of JDK 1.5, and its essence is the application of parameterized types (Parameterized Type) , that is to say, the data type being operated is specified as a parameter, and the specific type is specified when used. This parameter type can be used in the creation of classes, interfaces and methods, called generic classes, generic interfaces and generic methods respectively.

The idea of ​​generics began to take root as early as in the templates of the C++ language. When the Java language was in a version where generics had not yet appeared, Object could only be used as the parent class of all types. Type generalization can be achieved by combining the two features of type coercion. For example, in the access of hash tables, before JDK 1.5, the get() method of HashMap was used, and the return value was an Object object. Since all types in the Java language inherit from java.lang.Object, the Object can be transformed into any object. It’s possible in Chengdu. But because there are infinite possibilities, only the programmer and the virtual machine at runtime know what type of object this Object is. During compilation, the compiler cannot check whether the forced transformation of this Object is successful. If the programmer is solely relied on to ensure the correctness of this operation, many risks of ClassCastException will be transferred to the program runtime.

                                                                                                                                                                            The way of using generic technology in C # and Java seems to be the same, but there are fundamental differences in implementation. In C #, generics are used both in the program source code and in the compiled IL (Intermediate Language) , intermediate language, at this time generics are a placeholder) or in the CLR at runtime. List and List are two different types, which are generated during the system runtime. Having its own virtual method table and type data, this implementation is called type inflation, and the generics implemented based on this method are called real generics.

Generics in the Java language are different. They only exist in the program source code. In the compiled bytecode file, they have been replaced by the original raw type (Raw Type, also known as Naked type), and the cast code is inserted in the corresponding place, so for the Java language at runtime, ArrayList and ArrayList are the same class. Therefore, generic technology is actually a syntactic sugar of the Java language. The generic implementation method in the Java language is called type erasure, and the generics implemented based on this method are called pseudo-generics. (Type erasure will be studied later)

The program code written using the generic mechanism is more secure and safer than the code that messily uses Object variables and then performs forced type conversion. readability. Generics are especially useful for collection classes.

1. Why use generics

Here we look at a piece of code;

List list = new ArrayList();  
list.add("CSDN_SEU_Cavin");  
list.add(100);  
for (int i = 0; i < list.size(); i++) {  
  String name = (String) list.get(i); //取出Integer时,运行时出现异常  
System.out.println("name:" + name);  
}
Copy after login

This example uses the list type A string type value and an Integer type value are added to the collection. (This is legal because the default type of list is Object). In the subsequent loop, due to forgetting to add an Integer type value to the list before or for other reasons, a java.lang.ClassCastException exception will occur at runtime. To solve this problem, generics came into being.

2. The use of generics

Generics allow programmers to use type abstractions, usually used in collections.

List<String> list = new ArrayList<String>();
Copy after login

Written like this, the above loop value acquisition method will not report an error, and there is no need to perform type conversion. Through List, it is directly limited that the list collection can only contain elements of String type.

3. Generics are only valid during compilation

We also need to understand when using generics What happens when generics are compiled, so here, we need to pay special attention to: generics are only valid when the code is compiled into a class file

AyyayList<String> a = new ArrayList<String>();  
ArrayList b = new ArrayList();  
Class c1 = a.getClass();  
Class c2 = b.getClass();  
System.out.println(a == b);
Copy after login

The output of the above program is true. This is because all reflection operations are performed at runtime. Since it is true, it proves that after compilation, the program will take de-genericization measures.

In other words, generics in Java are only valid during the compilation phase. During the compilation process, after the generic results are correctly verified, the relevant information of the generics will be erased, and type checking and type conversion methods will be added at the boundaries of the object's entry and exit methods. In other words, The successfully compiled class file does not contain any generic information. Generic information does not enter the runtime phase.

The following code explains very well that generics are only valid during compilation through Java’s reflection mechanism

ArrayList<String> a = new ArrayList<String>();  
a.add("CSDN_SEU_Cavin");  
Class c = a.getClass();  
try{  
    Method method = c.getMethod("add",Object.class);  
    method.invoke(a,100);  
    System.out.println(a);  //[CSDN_SEU_Cavin, }catch(Exception e){  
    e.printStackTrace();
Copy after login

 4. Generics Classes and generic methods

public static class FX<T> {  
    private T ob; // 定义泛型成员变量  
  
    public FX(T ob) {  
        this.ob = ob;  
    }  
  
    public T getOb() {  
        return ob;  
    }  
  
    public void showTyep() {  
        System.out.println("T的实际类型是: " + ob.getClass().getName());  
    }  
}  
    public static void main(String[] args) {  
        FX<Integer> intOb = new FX<Integer>(100);  
        intOb.showTyep();  
        System.out.println("value= " + intOb.getOb());  //java.lang.Integer  System.out.println("----------------------------------");  
  
        FX<String> strOb = new FX<String>("CSDN_SEU_Calvin");  
        strOb.showTyep();  
        System.out.println("value= " + strOb.getOb());  //value= 100 } 
  
Copy after login

 5. Advantages of generics

     (1) Type safety.

By knowing the type restrictions of variables defined using generics, the compiler can more effectively improve the type safety of Java programs.

  (2) Eliminate forced type conversion.

Eliminate many casts in source code. This makes the code more readable and reduces the chance of errors. All casts are automatic and implicit.

  (3) Improve performance

The above is the detailed content of A closer look at generics in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles