J2SE: Java generics

xiaoxiao2021-03-06  23

Java generics

JDK1.5 makes us look for a long time, but when he is released, the version number is 5.0. This shows that Java has substantially change. This article will explain new features supported by JDK5.0 ---- Java's generic.

Java generics

In fact, Java's generics is a class that creates a class with a type as a parameter. Like the method we write, the method is such a Method (String Str1, String Str2), the value of the parameters STR1 and STR2 in the method is variable. The generic is also the same, which writes Class Java_Generics , which is also variable in the K and V on this. Let's take a look at the example:

Code List 1

Import java.util.hashtable;

Class testgen0 {

Public HashTable h = new hashtable ();

Public void Put (k K, v v) {

H.PUT (k, v);

}

Public V Get (kk) {

Return H.Get (k);

}

Public static void main (string args []) {

Testgen0 T = New TestGen0 ();

T.PUT ("Key", "Value");

String s = T. Get ("key");

System.out.println (s);

}

}

Correct output: Value

This is just an example (the collection framework in Java is generic, and it has been charged here. J), but see if it is a class that uses type as a parameter, the parameter is K, V, incoming "value" Is a String type. He does not have a specific type of payment. We used to define a class. In the input input parameters, it is fixed, but what is otherwise requested, but now write the program, it can not set the type of parameters, specifically It is time to determine, adding the versatility of the program, like a template. Oh, a template like C (similar).

Generic wildcard

Let's take a look at these procedures first:

Code List 2

Void TestGen0Medthod1 (List L) {

For (Object O: L)

System.out.println (O);

}

Look at this method, there is no objection, this method will be compiled, if you pass the String, this is like this List . Then we call it, the question will appear, we will pass a list as a method to the method, JVM will give us a warning, saying that this destruction type is safe, because it returns from the list is Object Type ,and. Let's take another way below.

Code List 3

Void TestGen0Medthod1 (List L) {

For (Object O: L)

System.out.println (O);

}

Because of the subclass of list , it is not the relationship between String and Object, that is, List is not affiliated to list , they are not inherited, so it's not good, here Extends It is limited to limit.

Type wilders are very magical, List What can you do for him? How is "?", It seems uncertain, he can't return one? As the type of data, it is ah, will he return a "?" To ask the programmer? JVM will make simple thinking, look at the code, it is more intuitive. Code List 4

List L1 = New ArrayList ();

li.add ("string");

List L2 = L1;

System.out.println (l1.get (0));

This code is no problem, L1.Get (0) will return an object.

Write generic classes to pay attention:

1. When defining a generic class, the form type parameters are defined between "<>", such as "Class Testgen ", where "K", "V" does not mean, but the type.

2. When instantiating generic objects, be sure to specify the value of the type parameters (type) after the class name, and have two written written. For example: Testgen t = new testgen ();

3. , Extends does not mean inheritance, which is a type limit.

Pancing and data type conversion

Eliminate type conversion

The above example everyone saw anything, the code of the data type conversion was not seen. We often have to write the following code, such as:

Code List 5

Import java.util.hashtable;

Class test {

Public static void main (String [] args) {

Hashtable h = new hashtable ();

H.PUT ("Key", "Value");

String s = (string) H.Get ("key");

System.out.println (s);

}

}

This type of conversion is very annoying, and forced type conversion will bring potential dangers, and the system may throw a classcastexception exception information. In JDK5.0, we can do this, such as:

Code List 6

Import java.util.hashtable;

Class test {

Public static void main (String [] args) {

Hashtable h = new hashtable ();

H.PUT ("Key", New Integer (123));

INT S = H.GET ("key"). INTVALUE ();

System.out.println (s);

}

}

Here we use the generalized version of HashMap, so don't use our code to write the type conversion code, the process of type conversion is handed over to the compiler, is it very convenient, and safe. The above is String mapped to String, or you can map the Integer to string, as long as you write a HashTable h = new hashtable (); h.Get (NEWEGER (0)) Returns Value. Sure enough. Automatic unpacking and automatic packaging

Didn't you see it from above, H.Get (New Integer (123)) here New Integer (123); I am so annoying, we can only bear it before JDK5.0, now this problem has been resolved Please see the following method. We have passed into this basic type, then add the value of i directly to the list, in fact, the list cannot store basic types, the object should be stored in the list, where the compiler will be packaged into Integer, then add it to the INT Go to the list. Then we use list.get (0); to retrieve data, and return to the object to unpack the object into int. Well, JDK5.0 brings us more convenient and safe.

Code List 7

Public void autoboxingunboxing (int i) {

ArrayList L = New ArrayList ();

L.Add (i);

INT A = L.GET (0);

System.out.println ("THE VALUE OF I IS" A);

}

Restrict the range of type parameters in generics

Maybe you have found Testgen of Code List 1, where K, V can be any type. Maybe you sometimes want to limit K and V of course, how to do it? Take a look at the following code:

Code List 8

Class Testgen2

{

Private v v = NULL;

PRIVATE K K = NULL;

Public void setv (v V) {

THIS.V = V;

}

Public v getv () {

Return this.v;

}

Public void setk (kk) {

THIS.K = K;

}

Public v getk () {

Return THISK;

}

Public static void main (string [] args)

{

Testgen2 T2 = New TestGen2 ();

NEW STRING ("String");

T2.SETV (New Integer (123));

System.out.println (t2.getk ());

System.out.println (T2.Getv ());

}

}

The range of the upper edge is <= String, V is <= Number, note that "<=", for K can be String, V Of course, Number, or INTEGER, FLOAT, DOUBLE, BYTE, etc.. Look at the picture below may be intuitive

Please see Figure A is the base class, A1, A2 in the topic, A1, A2, respectively, and 2 subclasses are A2_1, A2_2, respectively.

Then we define a restricted generic class mygen , this generic range is the middle map of the middle. This is a single restriction, you can also limit your number, as follows:

Class C & Serializable>

Let's analyze the following sentence, t extends comparable This is the limit of the upper limit, and Comparable This is the limit of the lower limit, serializable is the second upper limit. A specified type parameter can have one or more upper limits. Type parameters with multiple restrictions can be used to access each limitation of each limit.

Polymorphism

We can use type parameters to parameterize classes, and we can also use the type to parameterize the method. What will this look like? That is to say that the method of income parameters and return values ​​are generic, generic nature does not depend on any type of type information, and is different for each method call. Take a look at the code below, experience:

Code List 9

Class testgen {

Public Static List Make (t first) {

Return New List (first);

}

}

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

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