Generics 是JDK 1.5 一個最重要的特性,主要用來處理Collection。
以下代碼在JDK 1.5 調試通過。
代碼實例1: Demo.java
package maoxiang.examples.jdk15.generics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author 毛翔
*
* 演示如何使用Generics 特性。代碼來自於 Generics 教程:
* http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
*
* Generics類似於C++中的模板。
* 區別:
* 1.
* 2.
*/
public class Demo {
public static void main(String[] args) {}
/**
* 最簡單的用法
*/
public void Test1() {
// 以前的用法
//List myIntList = new LinkedList(); // 1
//myIntList.add(new Integer(0)); // 2
//Integer x = (Integer) myIntList.iterator().next(); // 3 需要強 制轉換
// 1.5 的用法
List<Integer> myIntList = new LinkedList<Integer>(); // 1’
myIntList.add(new Integer(0)); //2’
Integer x = myIntList.iterator().next(); // 3’
}
/**
* 匿名字符的用法
*/
public void Test2() {
List<Circle> list = new ArrayList<Circle>();
//通過匿名字符打印一個集合
Wildcards(list);
Wildcards1();
/*
* 如果 Wildcards2 定義為Wildcards2(List <Shape> shapes)
* 以下調用錯誤
*/
Wildcards2(list);
}
public void Wildcards(Collection< ? > c) {
// 以前的用法
//Iterator i = c.iterator();
//for (int k = 0; k < c.size(); k++) {
//
log(i.next());
//}
//1.5 的用法
//Collection<?> c 表示
for (Object e : c) {
log(e);
}
}
public void Wildcards1() {
//Collection<?> c = new ArrayList<String>();
//c.add(new Object()); // compile time error
//以上為錯誤的用法,因為不能確定 c 的類型 ,不能使用add ,但get可以 。正確的用法如下:
ArrayList<String> c = new ArrayList<String>();
c.add("test");
List< ? > list = c;
log(c.get(0));
}
public void Wildcards2(List< ? extends Shape> shapes) {
//List<Shape> shapes 定義只能接受List<Shape> shapes,也 不能接受 List<Circle>
for (Shape s : shapes) {
s.draw();
}
//以下寫法錯誤,因為為參數申明為 extends Shpape,無法確定Rectangle 為Shape子類,屬於不安全調用
//shapes.add(0, new Rectangle());
Map<String, Driver> allDrivers = new HashMap<String, Driver>();
Census.addRegistry(allDrivers);
//以下寫法允許,因為drivers明確定義,
List<Driver> drivers = new ArrayList<Driver>();
Census.add(drivers);
}
/**
* Generic Methods 的用法
*
*/
public void Test3() {
//適用於各種類型的函數
Object[] oa = new Object[100];
Collection<Object> co = new ArrayList<Object>();
fromArrayToCollection(oa, co);// T inferred to be Object
String[] sa = new String[100];
Collection<String> cs = new ArrayList<String>();
fromArrayToCollection(sa, cs);// T inferred to be String
fromArrayToCollection(sa, co);// T inferred to be Object
Integer[] ia = new Integer[100];
Float[] fa = new Float[100];
Number[] na = new Number[100];
Collection<Number> cn = new ArrayList<Number>();
fromArrayToCollection(ia, cn);// T inferred to be Number
fromArrayToCollection(fa, cn);// T inferred to be Number
fromArrayToCollection(na, cn);// T inferred to be Number
fromArrayToCollection(na, co);// T inferred to be Object
//test.fromArrayToCollection(na, cs);// 錯誤用法
}
public <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
//如果參數定義為 Collection< ? > c 以下寫法錯誤
c.add(o); // compile time error
}
}
/**
* generics 嵌套用法
* @param shapes
*/
public void drawAll(List< ? extends Shape> shapes) {
List<List< ? extends Shape>> history = new ArrayList<List< ? extends Shape>>();
history.add(shapes);
for (Shape s : shapes) {
s.draw();
}
}
/**
*
*
*/
public void Test4() {
List<String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.print(l1.getClass() == l2.getClass());
//打印為 true,
}
/**
* 錯誤用法
*/
public void Test5() {
Collection cs = new ArrayList<String>();
//以下為錯誤用法
//if (cs instanceof Collection<String>) { } // illegal
//以下為警告用法
//Collection<String> cstr = (Collection<String>) cs; // unchecked
// warning
}
public void Test6() {
//錯誤用法
//List<String>[] lsa = new List<String>[10]; // not really allowed
List< ? >[] lsa = new List< ? >[10]; // ok, array of unbounded wildcard
// type
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[1] = li; // correct
//String s = lsa[1].get(0); // run-time error - ClassCastException
//String s = lsa[1].get(0); // run time error, but we were warned
String s = (String) lsa[1].get(0); // run time error, but cast is
// explicit
}
public void Test7() {
Sink<Object> s = null;
Sink<String> s1 = null;
Collection<String> cs = null;
String str = writeAll(cs, s1);
//String str = writeAll(cs, s); // 無效調用
Object obj = writeAll1(cs, s); // 正確的調用
str = writeAll2(cs, s1); // 正確的調用
}
public <T> T writeAll(Collection<T> coll, Sink<T> snk) {
T last = null;
for (T t : coll) {
last = t;
snk.flush(last);
}
return last;
}
public <T> T writeAll1(Collection< ? extends T> coll, Sink<T> snk) {
T last = null;
for (T t : coll) {
last = t;
snk.flush(last);
}
return last;
}
public <T> T writeAll2(Collection<T> coll, Sink< ? super T> snk) {
T last = null;
for (T t : coll) {
last = t;
snk.flush(last);
}
return last;
}
// 打印
private void log(Object ob) {
System.out.print(ob);
}
}
//輔助定義
abstract class Shape {
public abstract void draw();
}
class Circle extends Shape {
private int x, y, radius;
public void draw() {
}
}
class Rectangle extends Shape {
private int x, y, width, height;
public void draw() {
}
}
class Person {}
class Driver extends Person {}
class Census {
public static void addRegistry(Map<String, ? extends Person> registry) {
}
public static void add(List< ? extends Person> persons) {
}
}
class Collections {
public static <T, S extends T> void copy(List<T> dest, List<S> src) {
}
}
代碼實例2。Sink.java
package maoxiang.examples.jdk15.generics;
/**
*
* @author 毛翔
*
* 定義一個接口模板,簡化了接口的定義
*
*/
interface Sink<E> {
public void flush(E t);
}
/*
* 如果是以前的定義,則要定義要各種類型的接口,顯然更麻煩
* interface Sink {
*
* public void flush(String str);
* public void flush(Object obj);
* public void flush(Integer test);
* ......
* }
*/