Home  >  Article  >  Java  >  What are generics in java

What are generics in java

little bottle
little bottleOriginal
2019-05-20 18:09:3216055browse

In the process of learning Java, I discovered a term called generics, but what are generics? Generics are a new feature of Java SE 1.5. I will take you to learn more about it below. Interested friends can learn about it. I hope it will be helpful to you.

What are generics in java

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

This parameter type can be used in the creation of classes, interfaces and methods, called generic classes, generic interfaces and generic methods respectively. The advantage of introducing generics into the Java language is safety and simplicity.

Before Java SE 1.5, in the absence of generics, the "arbitrary" parameter was implemented through a reference to the type Object. The disadvantage of "arbitrary" was that explicit coercion was required. Type conversion, and this conversion requires the developer to know the actual parameter type beforehand.

For forced type conversion errors, the compiler may not prompt an error, but an exception will occur during runtime. This is a security risk.

The advantage of generics is that type safety is checked at compile time, and all casts are automatic and implicit to improve code reuse.

Rule restrictions:

1. Generic type parameters can only be class types (including custom classes), not simple types.

2. The same generic type can correspond to multiple versions (because the parameter type is uncertain), and different versions of generic class instances are incompatible.

3. Generics can have multiple type parameters.

4. Generic parameter types can use the extends statement, such as . It is customary to call it a "bounded type".

5. The parameter type of a generic type can also be a wildcard type. For example, Class classType = Class.forName("java.lang.String");

Related learning recommendations: java basic tutorial

The above is the detailed content of What are 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