Java Basics Java Generics

Java generics (generics) is a new feature introduced in JDK 5. Generics provide a compile-time type safety detection mechanism, which allows programmers to detect illegal types at compile time. The essence of generics is that they are parameterized types, that is, the data type being manipulated 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 the generic method to sort an array of integers, floats, strings, and so on.



Generic Methods


You can write a generic method that can receive arguments of different types 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 method declarations have a type parameter declaration section (delimited by angle brackets) that precedes the method's return type

Each type parameter declaration section contains one or more types parameters, separated by commas. A generic parameter, also known as a type variable, is an identifier used to specify the name of a generic type. Type parameters can be used to declare the return type, and can be used as placeholders for the actual parameter types obtained by the generic method. Generic method bodies are declared like any other method. Note that type parameters can only represent reference types, not primitive types (int, double, char, etc.).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326278614&siteId=291194637