Generics is one of the most important features of JDK 1.5 and is mainly used to process collections.
The following code is successfully debugged in JDK 1.5.
Code Example 1: Demo. java
Package maoxiang. examples. jdk15.generics;
Import java. util. ArrayList;
Import java. util. Collection;
Import java. util. HashMap;
Import java. util. Collections list;
Import java. util. List;
Import java. util. Map;
/**
* @ Author Mao Xiang
*
* Demonstrate how to use the Generics feature. The code is from the Generics Tutorial:
* Http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
*
* Generics is similar to a template in C ++.
* Differences:
* 1.
* 2.
*/
Public class Demo {
Public static void main (String [] args ){}
/**
* Simplest usage
*/
Public void Test1 (){
// Previous usage
// List myIntList = new writable List (); // 1
// MyIntList. add (new Integer (0); // 2
// Integer x = (Integer) myIntList. iterator (). next (); // 3 needs to be forcibly converted
// Usage 1.5
List MyIntList = new parameter list (); // 1'
MyIntList. add (new Integer (0); // 2'
Integer x = myIntList. iterator (). next (); // 3'
}
/**
* Anonymous character usage
*/
Public void Test2 (){
List List = new ArrayList ();
// Print a set with anonymous characters
Wildcards (list );
Wildcards1 ();
/*
* If Wildcards2 is defined as Wildcards2 (List Shapes)
* The following call errors
*/
Wildcards2 (list );
}
Public void Wildcards (Collection <? > C ){
// Previous usage
// Iterator I = c. iterator ();
// For (int k = 0; k <c. size (); k ++ ){
//
Log (I. next ());
//}
// Usage 1.5
// Collection C Indicates
For (Object e: c ){
Log (e );
}
}
Public void Wildcards1 (){
// Collection C = new ArrayList ();
// C. add (new Object (); // compile time error
// The above is an incorrect usage. Because the c type cannot be determined, add cannot be used, but get can. The correct usage is as follows:
ArrayList C = new ArrayList ();
C. add ("test ");
List <? > List = c;
Log (c. get (0 ));
}
Public void Wildcards2 (List <? Extends Shape> shapes ){
// List Shapes definitions can only accept List Shapes, cannot accept List
For (Shape s: shapes ){
S. draw ();
}
// The following statement is incorrect. Because the parameter declaration is extends Shpape, it cannot be determined that the Rectangle is a Shape subclass and is an insecure call.
// Shapes. add (0, new Rectangle ());
Map AllDrivers = new HashMap ();
Census. addRegistry (allDrivers );
// The following statement is allowed, because drivers is clearly defined,
List Drivers = new ArrayList ();
Census. add (drivers );
}
/**
* Usage of Generic Methods
*
*/
Public void Test3 (){
// Applicable to various types of functions
Object [] oa = new Object [1, 100];
Collection