java泛型详细解析
[来源] 达内 [编辑] 达内 [时间]2012-11-09
泛型(Generic)
一、泛型的作用
JDK5中的泛形允许程序员在编写集合代码时,就限制集合的处理类型,从而把原来程序运行时可能发生问题,转变为编译时的问题,以此提高程序的可读性和稳定性(尤其在大型程序中更为突出)。
注意:泛型是提供给javac编译器使用的,它用于限定集合的输入类型,让编译器在源代码级别上,即挡住向集合中插入非法数据。但编译器编译完带有泛形的java程序后,生成的class文件中将不再带有泛形信息,以此使程序运行效率不受到影响,这个过程称之为“擦除”。
泛形的基本术语,以ArrayList
ArrayList
ArrayList
整个称为ArrayList
整个ArrayList
二、泛型典型应用
使用迭代器迭代泛形集合中的元素。
public void test1(){
List
list.add("wang");
list.add("hai");
list.add("yan");
Iterator
while(it.hasNext()){
String value=();
System.out.print(value);
}
}
使用增强for循环迭代泛形集合中的元素。
public void test2(){
Map map=new HashMap();
map.put(1, "wang");
map.put(2, "liu");
map.put(3, "meng");
Set> entries=map.entrySet();
for(Map.Entry entry:entries){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
存取HashMap中的元素。
public void test3(){
Map map=new HashMap();
map.put(1, "wang");
map.put(2, "liu");
map.put(3, "meng");
Set
Iterator
while(it.hasNext()){
int key=();
System.out.println(key+" "+map.get(key));
}
}
使用泛形时的几个常见问题:
使用泛形时,泛形类型须为引用类型,不能是基本数据类型
三、自定义泛形——泛型方法
Java程序中的普通方法、构造方法和静态方法中都可以使用泛型。方法使用泛形前,必须对泛形进行声明,语法:
public static
四、练习
1.编写一个泛形方法,实现数组元素的交换
public static
T temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String[] args) {
Integer arr[]={1,2,3,4};
test1(arr,0,2);
for(int ar:arr){
System.out.println(ar);
}
}
2.编写一个泛形方法,接收一个任意数组,并颠倒数组中的所有元素
public static
int startindex=0;
int endindex=arr.length-1;
for(;;){
if(startindex>=endindex){
break;
}
T temp=arr[startindex];
arr[startindex]=arr[endindex];
arr[endindex]=temp;
startindex++;
endindex--;
}
}
public static void main(String[] args) {
Integer arr[]={1,2,3,4};
test2(arr);
for(int ar:arr){
System.out.println(ar);
}
}
3、补充(将两个数字交换不设中间变量)
public static void testChange(){
int i=1000;
int j=1020;
i=i^j;
j=i^j;
i=i^j;
System.out.println(i+" "+j);
}
public static void main(String[] args) {
testChange();
}
五、注意
只有对象类型才能作为泛型方法的实际参数。
在泛型中可以同时有多个类型,例如:
public static V getValue(K key) { return map.get(key);}
如果一个类多处都要用到同一个泛型,这时可以把泛形定义在类上(即类级别的泛型),语法格式如下:
public class GenericDao
private T field1;
public void save(T obj){}
public T getId(int id){}
}
静态方法不能使用类定义的泛形,而应单独定义泛形。达内科技