1 class FormalCollection<E>{ 2 3 Object[] objects; 4 5 6 FormalCollection(){ 7 objects=new Object[5]; 8 } 9 10 public E getObjects(int index) { 11 return (E)objects[index]; 12 } 13 14 public void setObjects(E object,int index) { 15 objects[index] = object; 16 } 17 }
1 FormalCollection<String> formalCollectionString = new FormalCollection<>(); 2 3 formalCollectionString.setObjects("zhangsan",0); 4 formalCollectionString.setObjects("lisi",1); 5 formalCollectionString.setObjects("wanger",2); 6 formalCollectionString.setObjects("longwu",3); 7 8 FormalCollection<Integer> formalCollectionInteger = new FormalCollection<>(); 9 10 formalCollectionInteger.setObjects(25,0); 11 formalCollectionInteger.setObjects(26,1); 12 formalCollectionInteger.setObjects(27,2); 13 formalCollectionInteger.setObjects(28,3); 14 15 16 FormalCollection<Double> formalCollectionDouble = new FormalCollection<>(); 17 18 formalCollectionDouble.setObjects(12500.00,0); 19 formalCollectionDouble.setObjects(12600.00,1); 20 formalCollectionDouble.setObjects(12700.00,2); 21 formalCollectionDouble.setObjects(42800.00,3); 22 23 24 System.out.println("姓名"+"\t\t\t"+"年龄"+"\t\t\t"+"薪资"); 25 26 System.out.println(formalCollectionString.getObjects(0)+"\t"+formalCollectionInteger.getObjects(0)+"\t\t\t"+formalCollectionDouble.getObjects(0)); 27 System.out.println(formalCollectionString.getObjects(1)+"\t\t"+formalCollectionInteger.getObjects(1)+"\t\t\t"+formalCollectionDouble.getObjects(1)); 28 System.out.println(formalCollectionString.getObjects(2)+"\t\t"+formalCollectionInteger.getObjects(2)+"\t\t\t"+formalCollectionDouble.getObjects(2));
通过阅读源码,发现Collection、List、Set、Map、Iterator接口都定义了泛型
例子详情见ArrayList
JDK源码阅读-------自学笔记(十九)(容器概念初探和泛型概念)
原文:https://www.cnblogs.com/liuyangfirst/p/12927432.html