一、泛型是什么
Java泛型是JDK1.5引入的一个新特性,其本质是参数化类型,把类型作为参数传递
一些常用的泛型类型变量: E:元素(Element),多用于java集合框架 K:关键字(Key) N:数字(Number) T:类型(Type) V:值(Value)
语法:<T,…> T称为类型占位符,表示一种引用类型好处:① 提高代码的重用性。 ② 防止类型转换异常,提高代码的安全性。
二、常见形式
2.1 泛型类
public class MyGeneric<T> {
T t
;
public void show(T t
){
System
.out
.println(t
);
}
public T
getT(){
return t
;
}
}
public class TestGeneric {
public static void main(String
[] args
) {
MyGeneric
<String> myGeneric
= new MyGeneric<>();
myGeneric
.t
= "hello";
myGeneric
.show("大家好,加油!");
String string
= myGeneric
.getT();
System
.out
.println(string
);
MyGeneric
<Integer> myGeneric2
= new MyGeneric<>();
myGeneric2
.t
= 100;
myGeneric2
.show(200);
Integer integer
= myGeneric2
.getT();
System
.out
.println(integer
);
}
}
2.2 泛型接口
public interface MyInterface<T> {
String name
= "张三";
T
server(T t
);
}
实现方法形式一:
public class MyInterfaceImpl implements MyInterface<String> {
@Override
public String
server(String s
) {
System
.out
.println(s
);
return s
;
}
}
实现方法形式二:
public class MyInterfaceImpl2<T> implements MyInterface<T> {
@Override
public T
server(T t
) {
System
.out
.println(t
);
return t
;
}
}
public class TestGeneric {
public static void main(String
[] args
) {
MyInterfaceImpl impl
= new MyInterfaceImpl();
impl
.server("牛逼");
MyInterfaceImpl2
<Integer> impl2
= new MyInterfaceImpl2();
impl2
.server(1000);
}
}
2.3 泛型方法
public class MyGenericMethod {
public <T> T
show(T t
){
System
.out
.println("泛型方法" + t
);
return t
;
}
}
public class TestGeneric {
public static void main(String
[] args
) {
MyGenericMethod myGenericMethod
= new MyGenericMethod();
myGenericMethod
.show("中国加油");
myGenericMethod
.show(123);
myGenericMethod
.show(3.14);
}
}
三、泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。特点:① 编译时即可检查,而非运行时抛出异常。 ② 访问时,不必类型转换。 ③ 不同泛型之间引用不能相互赋值,泛型不存在多态。
使用
public class Demo3 {
public static void main(String
[] args
) {
ArrayList
<String> arrayList
= new ArrayList<String>();
arrayList
.add("xxx");
arrayList
.add("yyy");
for (String s
: arrayList
) {
System
.out
.println(s
);
}
ArrayList
<Student> arrayList2
= new ArrayList<Student>();
Student s1
= new Student("郭富城","21");
Student s2
= new Student("张国荣","23");
Student s3
= new Student("刘德华","24");
arrayList2
.add(s1
);
arrayList2
.add(s2
);
arrayList2
.add(s3
);
Iterator
<Student> it
= arrayList2
.iterator();
while (it
.hasNext()) {
Student next
= it
.next();
System
.out
.println(next
);
}
}
}