泛型
Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。常见形式有泛型类、泛型接口、泛型方法。语法:
<T,…>T称为类型占位符,表示一种引用类型。 好处:
(1)提高代码的重用性(2)防止类型转换异常,提高代码的安全性
public class Demo08<T> {
T t
;
public void show(T t
){
System
.out
.println(t
);
}
public T
getT(){
return t
;
}
}
public class TestDemo08 {
public static void main(String
[] args
) {
Demo08
<String> demo08
= new Demo08<String>();
demo08
.t
="hello";
demo08
.show("大家好,加油!");
String string
= demo08
.getT();
Demo08
<Integer> demo082
= new Demo08<Integer>();
demo082
.t
= 100;
demo082
.show(100);
Integer integer
= demo082
.getT();
}
}
泛型接口
public interface MyInterface<T> {
String name
= "张三";
T
server(T t
);
}
public class MyInterfaceImpl implements MyInterface<String>{
@Override
public String
server(String t
) {
System
.out
.println(t
);
return t
;
}
public static void main(String
[] args
) {
MyInterfaceImpl impl
= new MyInterfaceImpl();
impl
.server("xxxxx");
}
}
public class MyInterfaceImpl2<T> implements MyInterface<T>{
@Override
public T
server(T t
) {
System
.out
.println(t
);
return t
;
}
public static void main(String
[] args
) {
MyInterfaceImpl2
<Integer> impl2
= new MyInterfaceImpl2<>();
impl2
.server(1000);
}
}
泛型方法
public class MyGenericMethod {
public<T> T
show(T t
){
System
.out
.println("泛型方法: "+t
);
return t
;
}public static void main(String
[] args
) {
MyGenericMethod myGenericMethod
= new MyGenericMethod();
myGenericMethod
.show("中国");
myGenericMethod
.show(100);
myGenericMethod
.show(3.14);
}
}
泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。特点:
编译时即可检查,而非运行时抛出异常。访问时,不必类型转换(拆箱)。不同泛型之间引用的数据不能相互赋值,泛型不存在多态。
import java
.util
.ArrayList
;
import java
.util
.Iterator
;
public class Demo09 {
public static void main(String
[] args
) {
ArrayList
<String> arraylist
= new ArrayList<String>();
arraylist
.add("xxx");
arraylist
.add("yyy");
for (String string
:arraylist
) {
System
.out
.println(string
);
}
ArrayList
<Student> arraylist2
= new ArrayList<Student>();
Student s1
= new Student("张三",20);
Student s2
= new Student("张无忌",18);
Student s3
= new Student("王三",22);
arraylist2
.add(s1
);
arraylist2
.add(s2
);
arraylist2
.add(s3
);
Iterator
<Student> iterator
=arraylist2
.iterator();
while(iterator
.hasNext()){
Student s
= iterator
.next();
System
.out
.println(s
);
}
}
}