1 泛型(Generic) 1.1 说明 增强了java的类型安全,可以在编译期间对容器内的对象进行类型检查,在运行期不必进行类型的转换。而在j2se5之前必须在运行期动态进行容器内对象的检查及转换 减少含糊的容器,可以定义什么类型的数据放入容器 ArrayList<Integer> listOfIntegers; // <TYPE_NAME> is new to the syntax Integer integerObject; listOfIntegers = new ArrayList<Integer>(); // <TYPE_NAME> is new to the syntax listOfIntegers.add(new Integer(10)); // 只能是Integer类型 integerObject = listOfIntegers.get(0); // 取出对象不需要转换 1.2 用法 声明及实例化泛型类: HashMap<String,Float> hm = new HashMap<String,Float>(); //不能使用原始类型 GenList<int> nList = new GenList<int>(); //编译错误 J2SE 5.0目前不支持原始类型作为类型参数(type parameter) 定义泛型接口: public interface GenInterface<T> {
void func(T t); } 定义泛型类: public class ArrayList<ItemType> { ... }
public class GenMap<T, V> { ... } 例1: public class MyList<Element> extends LinkedList<Element>
{ public void swap(int i, int j) { Element temp = this.get(i); this.set(i, this.get(j)); this.set(j, temp); }
public static void main(String[] args) { MyList<String> list = new MyList<String>(); list.add("hi"); list.add("andy"); System.out.println(list.get(0) + " " + list.get(1)); list.swap(0,1); System.out.println(list.get(0) + " " + list.get(1)); } } 例2: public class GenList <T>{
private T[] elements; private int size = 0; private int length = 0;
public GenList(int size) { elements = (T[])new Object[size]; this.size = size; }
public T get(int i) { if (i < length) { return elements[i]; } return null; }
public void add(T e) { if (length < size - 1) elements[length++] = e; } } 泛型方法: public class TestGenerics{
public <T> String getString(T obj) { //实现了一个泛型方法 return obj.toString(); }
public static void main(String [] args){ TestGenerics t = new TestGenerics(); String s = "Hello"; Integer i = 100; System.out.println(t.getString(s)); System.out.println(t.getString(i)); } }
|