J2SE5.0 instance --- generic

xiaoxiao2021-03-06  21

Introduction

The generic is not a new language element, and C will have morning, but Java after C has not absorbed this feature. Now Java has a generic feature, which is probably related to .NET competition. .

First look at a generic application.

In the past, we may often write some code like this:

List stringlist (); stringlist.add ("firststring"); stringlist.add ("secondstring"); string str = (String) stringlist.iterator (). Next ();

In fact, the third line is not a lot of conversion significance for String, because usually if we do a list, you know what type of objects put in this list, but if we don't write, you will pass the grammatical check.

Using Java's generic mechanism, we can write this:

List stringlist = new linkedList (); stringlist.add ("firststring"); stringlist.add ("secondstring"); string str = stringlist.iterator (). Next ();

The advantage of this is that when defining the container, it indicates the type in the container. On the other hand, we no longer need to take an element to make a mandatory type conversion, and on the other hand, if the object type placed in this container does not meet the requirements, Then you will generate an error during compile, not an exception is thrown during the run.

In addition, it also improves the readability of the program.

General type definition

Here is a simple definition of generic classes:

Public class mygenericclass {private t value; public t getValue () {Return Value;} PUBLIC VOID SETVALUE (T value) {this.Value = value;}}

It is worth noting that static variables cannot be defined using generic definitions, that is to say that the following statements are illegal:

Public Class MyGenericClass {public static t value; // Error definition}

In addition, the definition of generics will not be inherited, and for example, if a is a subclass of B, C is a type of generic definition, c is not a subclass of C . For a better description, you can look at the following code, this code is wrong.

List strlist = new arraylist (); list Objlist = strlist; // Error assignment

However, such a code is correct:

List strlist = new arraylist (); strlist.add ("a string");

Assign type

Suppose we need such a function, use it to print all the elements in a collection, before we may define this:

Void PrintCollection (Collection C) {Iterator i = C.Iterator (); for (k = 0; k

Void PrintCollection (Collection C) {for (Object E: C) {System.out.Println (E);}}

But there is a problem. If we now have an object type is Collection , we cannot pass it as a parameter to PrintCollection because Collection is not the subclass of Collection .

In order to solve this problem, we can use the custom type?, That is, defined below this:

Void PrintCollection (Collection c) ​​{for (Object E: c) {system.out.println (e);}}

It can be said that Collection Is the parent class of all Collection.

Let's take a look at the code below.

Private Void CleaLMAPS (Collection c) {for (Map M: c) {m.clear ();}}

There is no doubt that it also has the problem we say above, that is, the subclass of HashMap is unable to operate, but if we change the parameters to Collection Is not reasonable, because we only hope to the father The class is operated as a subclass of MAP, then we can rewrite this:

PRIVATE VOID CLEARALLMAPS (Collection C) {for (Map M: c) {m.clear ();}}

A consecutive harmonic similar to? Extends MAP is called a qualified custom type.

Suppose an object h type is Collection , then we pass H as a parameter to CleaLLMAPS, as shown in the following segment:

List > h = new arraylist > (); hashmap m = new hashmap (); m.put ("key", "value"); H.Add (m); ClearalLmaps (h);

For methods used above, use? Extend XXX, it is worth noting that it is not possible to replace the sub-objects of XXX in the method. As with the code below is wrong:

Public void addRectangle (list Shapes) {shapes.add (0, new reccTangle ()); // Error usage!}

Here we assume that Rectangle is a subclass of Shape.

The reason why this writing is not allowed is relatively simple because the parameter type may be another subclass of Shape when calling this method. If Shape has another subclass Circle other than Rectangle this subclass, then we can pass a list type of object as a parameter to this method (note that it is legal), but in the method, The Rectangle object is placed in Shapes, which is obviously unreasonable. In addition to Extends, you can also use the Super key in the generic parameter type, refer to the following sequence:

PRIVATE VOID ADDSTRING (Collection c) {C.Add ("a string");}

Generic function

We mentioned the type of customization, now let us make a function, it implements such a function, add the elements in an array to a collection, in order to ensure the versatility of the program, we may write another error Code:

Private Void fromArrayTocollection (Object [] A, Collection c) ​​{for (Object O: a) {C.Add (o); // Error code}}

So what should this function write? We can implement the method of adding generic parameters to functions, as shown below:

Private Void ExfromArrayTocollection (T [] A, Collection C) {for (t o: a) {c.add (o); // This is correct}}

So, when should we use a custom type, when should we use a generic function? The answer is depends on the type dependence between the function parameters and the return value between the function parameters.

If the parameter type of a function is not necessarily associated with the parameters returned by the function, the type of other parameters other than the function is not dependent, then we should use a homer, otherwise the generic function should be used.

In order to clearly explain this, we can take a look at the definition of several methods in the java.util package:

Class collections {static void swap (list list, int i, int j) {...} static void copy (list dest, list src) {.. }

The SWAP function can actually define this:

Static Void Swap (List List, INT I, INT J) {...}

However, it is noted that the generic type parameter T is used only in the parameter, which means that it is not dependent on other parts of the function, which can be seen as a sign we should use.

In the copy method, the element in the copy source SRC must be that the DEST can be accepted, the elements in the SRC must be a subclass of T, but which is specifically which subclasses we don't have to care, so use generics in the method As a type of parameters, it also uses a custom type as a second type of parameters.

转载请注明原文地址:https://www.9cbs.com/read-45991.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.035, SQL: 9