Java generic learning.

Source: Internet
Author: User
Tags getv

New features supported by JDK-Java generics

Here is an example written by myself:

Bytes --------------------------------------------------------------------------------------------------------------

Package test;

Import java. util. hashtable;
Import java. util. Random;

Public class test {
 
Public hashtable <string, string> H = new hashtable <string, string> ();

Public void put (string K, string v ){

For (INT I = 0; I <5; I ++ ){

Random S = new random ();

H. Put (string. valueof (I), String. valueof (S. nextint (100 )));

}

}

Public String get (string K ){

Return H. Get (k );

}

 
Public static void main (string ARGs []) {

Test T = new test ();

T. Put ("","");

For (INT I = 0; I <5; I ++ ){

System. Out. println (T. Get (string. valueof (I )));

}


}

}

Bytes -----------------------------------------------------------------------------------------------------------------------------

Package test;
Import java. Lang. number;

Public class Test2 <k extends string, V extends number> {

Private V v = NULL;

Private K = NULL;

Public void setv (V v ){

This. V = V;

}

Public v getv (){

Return this. V;

}

Public void setk (K ){

This. k = K;

}

Public K getk (){

Return this. K;

}


Public static void main (string [] ARGs ){

Test2 <string, integer> T = new Test2 <string, integer> ();

T. setk ("Haha ");

T. setv (New INTEGER (800 ));

System. Out. println (T. getk ());

System. Out. println (T. getv ());



}

}

Bytes ------------------------------------------------------------------------------------------------------------------------------

1. Java generic

In fact, Java generic is to create a class with the type as the parameter. Just like the method of writing a class, the method is such a method (string str1, string str2). The values of str1 and str2 in the method are variable. The same is true for generics. In this way, writing class java_generics <K, V> is like the str1 and str2 parameters in the method. The following is an example:

// Code List 1

Import java. util. hashtable;

Class testgen0 <K, V> {

Public hashtable <K, V> H = new hashtable <K, V> ();

Public void put (K, V v ){

H. Put (K, V );

}

Public v get (K ){

Return H. Get (k );

}

Public static void main (string ARGs []) {

Testgen0 <string, string> T = new testgen0 <string, string> ();

T. Put ("key", "value ");

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

System. Out. println (s );

}

}

Correct output: Value

This is just an example (Java integration frameworks are all generic, and I have spent two times here .), but check whether a class with the type as the parameter is created. The parameter is K and V, and the input "value" is of the string type. This class does not have a specific type to be processed. We have defined a class in the past, and the input parameters are fixed. What type is required? But now we write a program, you can choose not to specify the parameter type. It is determined when it is used. This increases the universality of the program, such as a template.

Haha, similar to the C ++ template (similar ).

1.1. wildcard

Let's take a look at these programs:

// Code List 2

Void testgen0medthod1 (list l ){

For (Object O: l)

System. Out. println (O );

}

Check whether there is any objection to this method. This method will be compiled. If you input a string, this is the list <string>.

Then we call it, and the problem arises. We pass a list <string> As a list to the method. JVM will give us a warning that this destroys the type security, because the objects returned from the list are of the object type, let's look at the following method.

// Code list 3

Void testgen0medthod1 (list <string> L ){

For (Object O: l)

System. Out. println (O );

}

Because the list <string> here is not a subclass of list <Object>, it is not the relationship between string and object, that is, list <string> is not a part of list <Object> and they are not an inheritance relationship, so no, the extends here indicates the limitation.

The Type wildcard is amazing. List <?> What can you do for him? Why are they all "?", It seems uncertain. He cannot always return one? As the type of data, right? He will not return a "?" Ask the programmer? JVM will do some simple thinking. Let's look at the code, which is more intuitive.

// Code list 4

List <string> L1 = new arraylist <string> ();

Li. Add ("string ");

List <?> L2 = L1;

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

If this code is correct, l1.get (0) returns an object.

1.2. Notes for compiling generic classes:

1) when defining a generic class, define the formal type parameters between "<>", for example, "Class testgen <K, V>", where "K ", "V" does not represent a value, but a type.

2) when instantiating a generic object, you must specify the value (type) of the type parameter after the class name, which must be written twice in total. For example:

Testgen <string, string> T = new testgen <string, string> ();

3) in the generic <k extends Object>, extends does not represent inheritance. It is a type range restriction.

2. Generic and data type conversion

2.1. Eliminate type conversion

What did you see in the above example? The data type conversion code is gone. In the past, we often had to write the following code, such:

// 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 );

}

}
We have made a type conversion, isn't it annoying, and forced type conversion may bring potential danger, the system may throw a classcastexception information. In jdk5.0, we can do this completely, for example:

// Code list 6

Import java. util. hashtable;

Class test {

Public static void main (string [] ARGs ){

Hashtable <string, integer> H = new hashtable <string, integer> ();

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 we don't need to write the type conversion code. The type conversion process is handed over to the compiler for processing. It is convenient and safe. The above is a string ing to a string, you can also map an integer to a string, as long as it is written as hashtable <integer, string> H = new hashtable <integer, string> (); H. get (New INTEGER (0) returns value. It is really convenient.

2.2 automatic unpackaging and automatic Packaging

Is it awkward to see from above? H. get (New INTEGER (123) The new INTEGER (123) Here is annoying. We can only endure it before jdk5.0. Now this problem has been solved. Please refer to the following method. We pass in a basic type of int, and then add the I value to the List directly. In fact, the list cannot store the basic type, and the object should be stored in the list, here, the compiler wraps the int into an integer and adds it to the list. Then we use list. Get (0); to retrieve the data, return the object, and decompile the object into Int. Well, jdk5.0 brings us more convenience and security.

// Code list 7

Public void autoboxingunboxing (int I ){

Arraylist <integer> L = new arraylist <integer> ();

L. Add (I );

Int A = L. Get (0 );

System. Out. println ("the value of I is" + );

}

2.3 limit the range of type parameters in generics

You may have discovered the testgen <K, V> generic class in code list 1, where K, V can be any type. Maybe you want to limit the range of K and V. How can this problem be solved? Take a look at the following code:

// Code List 8

Class testgen2 <k extents string, V extends number>

{

Private V v = NULL;

Private K = NULL;

Public void setv (V v ){

This. V = V;

}

Public v getv (){

Return this. V;

}

Public void setk (K ){

This. k = K;

}

Public v getk (){

Return this. K;

}

Public static void main (string [] ARGs)

{

Testgen2 <string, integer> T2 = new testgen2 <string, integer> ();

T2.setk (new string ("string "));

T2.setv (New INTEGER (123 ));

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

System. Out. println (t2.getv ());

}

}

The range of K above is <= string, and the range of V is <= number. Note that it is "<=". K can be string, and V can also be number, it can also be integer, float, double, byte, etc. For more information, see that A is the base class in the class. A1 and A2 are the sub-classes of A respectively. A2 has two sub-classes: a2_1 and a2_2.

Then we define a restricted generic class mygen <E extends A2>. The range of this generic class is the blue part.

This is a single restriction. You can also set multiple types as follows:

Class C <t extends comparable <? Super T> & serializable>

Let's analyze the following sentence. t extends comparable is the upper limit, comparable <super T> is the lower limit, and serializable is the 2nd upper limit. A specified type parameter can have one or more upper limits. A type parameter with multiple restrictions can be used to access each of its restricted methods and domains.

2.4. polymorphism Method

// Code List 9

Class testgen {

<T extends Object> Public static list <t> make (t first ){

Return new list <t> (first );

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.