Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the generic features of Java

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "what are the generic features of Java". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the generic features of Java?"

1. Define

Before we know something, we must know its definition, so we start with the definition and unravel the mystery of generics step by step.

# generics (generics)

It is a new feature introduced in JDK5. Generics provide a compile-time type safety monitoring mechanism that allows us to detect illegal type data structures at compile time. The essence of generics is a parameterized type, that is, the data type being operated is specified as a parameter # the common generic type indicates that the above T is only similar to the function of a formal parameter, and the name can actually be arbitrary. But we should always write code to pay attention to readability. The common parameters are: e-Element (used in the collection because elements are stored in the collection) T-Type (representing Java classes, including basic classes and our custom classes) K-Key (representing keys, such as key in Map) V-Value (representing values)?-(representing uncertain java types) but generic parameters can only be class types, not basic data types, and their types must be from Object.

Note: generics do not accept basic data types, in other words, only reference types can be used as actual parameters of generic methods.

two。 Why use generics?

When it comes to why to use it, it must be to find a lot of advantages that can convince yourself.

The introduction of generics is a big feature enhancement for the java language. At the same time, it also brings some enhancements to the compiler. In order to support generics, java's class libraries have been modified to support generics. (popular science: in fact, java generics were not put forward by jdk5 (2004 released jdk5). As early as 1999, the generics mechanism was one of the earliest specifications of java.

In addition, generics have the following advantages:

# 1. Submitted type safety for java

Generics greatly improve the program security of java. For example, in the absence of generics, it is easy to convert the string 123 to Integer type 123 or Integer to String, and such errors cannot be detected at compile time. Using generics can avoid this situation very well.

# 2. No annoying cast is required

Generics can eliminate forced type conversions because programmers already know the specific types they use at the time of development, which not only improves the readability of the code, but also increases the robustness of the code.

# improved code reusability

Generic programming means that the code written can be reused by many different types of objects

Before the formal release of the generic specification, generic programming was implemented through inheritance, but there were two serious problems:

You need to cast when you take the value of ①, otherwise all you get is Object

There will be no error checking during ② compilation.

Let's take a look at the generation of these two errors.

2.1 there will be no error checking during compilation

Public class DonCheckInCompile {public static void main (String [] args) {List list = new ArrayList (); list.add ("a"); list.add (3); System.out.println (list);}}

The program not only will not report an error, but also can output normally.

2.2 forced type conversion

Public class DonCheckInCompile {public static void main (String [] args) {List list = new ArrayList (); list.add ("a"); list.add (3); for (Object o: list) {System.out.println ((String) o);}

Because you don't know what types of elements in the actual collection are, you are uncertain when using them. If you make a strong turn, it will inevitably lead to unexpected errors, so the potential problem is like a ticking time bomb. It must not be allowed to happen. So this reflects the importance of generics.

3. Generic method

In java, generic methods can be used in member, constructor, and static methods. The syntax is as follows:

The public type parameter fun (); such as publicT fun (T t); where T represents a generic type, which means that we have defined a type of T, so that the T type can be used directly and needs to be placed before the return type of the method. T, that is, you don't know the specific type when you declare it, and only when you use it, you can know its type. T is not a class, but it can be used as a type.

The following code exchanges the elements of the two specified subscript positions in the array (regardless of what the actual requirements are), the first Integer type array.

Public class WildcardCharacter {public static void main (String [] args) {Integer [] arrInt = {1,2,3,4,5,6,7,8,9}; change (arrInt, 0,8); System.out.println ("arr =" + Arrays.asList (arrInt)) } / * Exchange elements in the array with specified two subscript positions * * @ param arr array * @ param firstIndex first subscript * @ param secondIndex second subscript * / private static void change (Integer [] arr, int firstIndex, int secondIndex) {int tmp = arr [firstIndex]; arr [firstIndex] = arr [secondIndex] Arr [secondIndex] = tmp;}}

The second is an array of type String

Compilation will not pass directly, that is inevitable, because the parameter defined by the method is Integer []. As a result, you pass a String [], playing. So at this point, you can only define another parameter type that is String [].

What about another Double? what about Boolean? Is this a problem? although this problem is not fatal and can be solved by writing more repetitive code, it is bound to lead to code redundancy and an increase in maintenance costs. So the role of generics at this time reflects the way we change it to generics.

/ * * @ param t parameter type T * @ param firstIndex first subscript * @ param secondIndex second subscript * @ param means that a type of type T is defined, otherwise no one knows what T is and the compilation time does not know * / private static void changeT (T [] t, int firstIndex, int secondIndex) {T tmp = t [firstIndex] T [firstIndex] = t [secondIndex]; t [secondIndex] = tmp;}

Then the call is simple.

Public static void main (String [] args) {/ / first define an array of type Integer Integer [] arrInt = {1, 2, 3, 4, 5, 6, 7, 8, 9}; / / swap the elements of the 1st and 9th positions changeT (arrInt, 0,8); System.out.println ("arrInt =" + Arrays.asList (arrInt)) / then after defining an array of String type String [] arrStr = {"a", "b", "c", "d", "e", "f", "g"}; / / swap the elements of the 1st and 2nd positions changeT (arrStr, 0,1); System.out.println ("arrStr =" + Arrays.asList (arrStr));}

The problem is easily solved, as for ordinary generic methods and static generic methods are used the same, but a data class belongs to an instance of the class, there is little difference in use (but it should be noted that if static generic methods in generic classes cannot use generic types in class generics, which will be described in more detail in generic classes below).

Finally, let's take a look at the construction method.

Public class Father {public Father (T t) {}}

And then suppose he has a subclass that looks like this.

Class Son extends Father {public Son (T t) {super (t);}}

To emphasize here, because there is no nonparametric constructor in the Father class, it is replaced by a parameterized constructor, but this constructor is a generic method, so such a subclass must need to show a specified constructor.

Get the element test in the collection through the generic method

Since generics are stated when the type is not the key point, as long as things are sure when they are used, how do you explain the following?

At this point, I want to add elements to the collection, but prompt such an error that I can't even compile it. Why is that?

Because the add method of the collection List at this time, the added type is T, but it is obvious that T is a generic type, and the real type can only be determined when it is used, but the type of T cannot be determined in add, so it is impossible to use the add method at all, unless list.add (null), but this does not make any sense.

4. Generic class

First, let's take a look at a piece of code like this, which uses multiple generic methods, without paying attention to what the methods do.

Public class GenericClassTest {public static void main (String [] args) {/ / first define an array of type Integer Integer [] arrInt = {1, 2, 3, 4, 5, 6, 7, 8, 9}; / / swap the elements at the 1st and 9th positions for new GenericClassTest (). ChangeT (arrInt, 0,8); System.out.println ("arrInt =" + Arrays.asList (arrInt)) List list = Arrays.asList ("a", "b"); testIter (list) } / * * @ param t parameter type T * @ param firstIndex first subscript * @ param secondIndex second subscript * @ param indicates that a type of type T is defined, otherwise no one knows what T is I don't know * / private void changeT (T [] t, int firstIndex, int secondIndex) {T tmp = t [firstIndex] at compile time. T [firstIndex] = t [secondIndex]; t [secondIndex] = tmp } / * traversal collection * * @ param list collection * @ param means that a type of type T is defined, otherwise no one knows what T is and the compilation time does not know * / private static void testIter (List list) {for (T t: list) {System.out.println ("t =" + t) }

You can see whether each method needs to be declared once, and what if there are 100 methods? Does that have to be declared 100 times, so that the generic class will be applied? What does the form of a generic class look like? Please look at the code

Public class GenericClazz {/ / this is what a basic generic class looks like.

Below we will optimize the code as follows, but here we have to say a very basic, but few people notice the problem, please see the text description section in the screenshot below.

# Why does the instance method work but the static method reports an error? 1. First of all, let me tell you the conclusion: static methods cannot use class-defined generics, but should define generics 2. 5 separately. At this point, it is estimated that many friends will understand in an instant, because static methods are called directly through the class, while ordinary methods must be called through instances. When the class calls the static method, the subsequent generic class has not yet been created. So you can't call it that way.

So the static method in this generic class can be written like this directly.

/ * traversal collection * * @ param list collection * / private static void testIter (List list) {for (K t: list) {System.out.println ("t =" + t);}}

Use multiple generic types at the same time

We know that Map exists in the form of key-value pairs, so what if we use generic types for both Key and Value of Map? The same use, a static method can be done, please see the following code

Public class GenericMap {private static void mapIter (Map map) {for (Map.Entry kvEntry: map.entrySet ()) {K key = kvEntry.getKey (); V value = kvEntry.getValue (); System.out.println (key + ":" + value);} public static void main (String [] args) {Map mapStr = new HashMap () MapStr.put ("a", "aa"); mapStr.put ("b", "bb"); mapStr.put ("c", "cc"); mapIter (mapStr); System.out.println ("="); Map mapInteger = new HashMap (); mapInteger.put (1, "11"); mapInteger.put (2, "22") MapInteger.put (3, "33"); mapIter (mapInteger);}}

At this point, generic methods and generic classes have been introduced for.

5. Wildcard character

Wildcards? That is, the meaning of a placeholder, that is, its type cannot be determined during use, as long as the type is specified in the actual use in the future, it has three forms.

Unqualified wildcards. Is to enable generics to accept data of unknown types.

< ? extends E>

A wildcard with an upper limit. Can accept data of the specified class and its subclass types, and E is the upper boundary of the generic type

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report