Home  >  Article  >  Java  >  How to define generics in java

How to define generics in java

藏色散人
藏色散人Original
2019-05-31 13:20:014315browse

Generics are a new feature of Java SE 1.5. The definition of generics in "Java Core Technology" is: "Generics" means that the code written can be reused by different types of objects.

How to define generics in java

Java generics are a new feature introduced in JDK 5. Generics provide a compile-time type safety detection mechanism, which allows programmers to Illegal type detected.

The essence of generics is a parameterized type, which means that the data type being operated on is specified as a parameter.

Suppose we have such a requirement: write a sorting method that can sort integer arrays, string arrays or even any other type of array. How to implement it?

The answer is that you can use Java generics.

Using the concept of Java generics, we can write a generic method to sort an array of objects. Then, call this generic method to sort an array of integers, arrays of floats, arrays of strings, etc.

Generic method

You can write a generic method that can receive different types of parameters when called. Depending on the parameter types passed to the generic method, the compiler handles each method call appropriately

The following are the rules for defining generic methods:

All generic methods Each declaration has a type parameter declaration part (separated by angle brackets) that precedes the method's return type ( in the example below).

Each type parameter declaration part contains one or more type parameters, separated by commas. A generic parameter, also called a type variable, is an identifier that specifies the name of a generic type.

Type parameters can be used to declare return value types and can be used as placeholders for the actual parameter types obtained by generic methods.

The declaration of a generic method body is the same as that of other methods. Note that type parameters can only represent reference types, not primitive types (such as int, double, char, etc.).

The above is the detailed content of How to define generics in java. For more information, please follow other related articles on 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