泛型
- Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。
- 常见形式有泛型类、泛型接口、泛型方法。
- 语法:
- <T ,… >T称为类型占位符,表示一种引用类型。
- 好处:
- 提高代码的重用性
- 防止类型转换异常,提高代码的安全性
泛型类
/**
* 泛类型
* 语法:类名<T>
* T是类型占位符,表示一种引用类型,如果编写多个使用逗号隔开
* */
public class MyGeneric<T> {
//使用泛类型T
//1创建变量
T t;
//2泛型作为方法的参数
public void show(T t){
//T t1 = new T(); //不能实例化,因为不确定这个到底传过来的参数能不能用。
System.out.println(t);
}
//3泛型作为方法的返回值
public T getT(){
return t;
}
}
public class TestGeneric {
public static void main(String[] args) {
//使用泛型类创建对象
//注意:1泛型只能使用引用类型。2不同泛型类型对象之间不能相互赋值
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t="hello";
myGeneric.show("大家好,加油");
String string = myGeneric.getT();
MyGeneric<Integer> myGeneric1 = new MyGeneric<Integer>();
myGeneric1.t = 100;
myGeneric1.show(200);
Integer integer = myGeneric1.getT();
}
}
泛型接口
语法:接口名
注意:不能泛型静态常量
/**
* 泛型接口
* 语法:接口名<T>
* @author wgy
* */
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 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("xxxxx");
MyInterfaceImpl2 impl2 = new MyInterfaceImpl2();
impl2.server(123);
}
}
泛型方法
语法: 返回值类型
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("dadasd");//自动类型为字符串
myGenericMethod.show(123);//integer类型
myGenericMethod.show(true);//double类型
}
}
泛型集合
- 概念:参数化类型、类型安全的集合,强制类型的集合必须一致。
- 特点
- 编译时即可检查,而非运行时抛出异常。
- 访问时,不必类型转换(拆箱)。
- 不同泛型之间引用不能相互赋值,泛型不存在多态。
public class Demo5 {
public static void main(String[] args) {
ArrayList<Student> arrayList2 = new ArrayList<Student>();//将泛型,定义成Student类
Student s1 = new Student("大师傅",3223);
Student s2 = new Student("小商贩",33);
arrayList2.add(s1);
arrayList2.add(s2);
Iterator<Student> it = arrayList2.iterator();
while (it.hasNext()){
Student f = it.next();
System.out.println(f.toString());
}
}
}