泛型
是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。
常见形式有泛型类,泛型接口,泛型方法
语法:
<T,…>T称为类型占位符,表示一种引用类型。
好处:
1)提高代码的重用性;
2)防止类型转换异常,提高代码的安全性。
泛型类
/**
* 泛型类
* 语法:类命<T>
* T是类型占位符,表示一种引用类型,如果写多个使用逗号隔开
*/
public class MyGeneric<T>{
//使用泛型T
//1 创建变量
T t;
//2 作为方法的参数
public void show(T t){
System.out.println(t);
}
//泛型作为方法的返回值
public T getT(){
return t;
}
}
public class TestGeneric{
public static void main(String[] args){
//使用泛型创建对象
//注意:1 泛型只能使用引用类型 2 不同泛型对象不能相互复制
MyGeneric<String> myGeneric=new MyGeneric<String>();
myGeneric.t="world";
mtGeneric.show("大家好");
String string=myGeneric.getT();
MyGeneric<Integer> myGeneric2=new MyGeneric<Integer>();
myGeneric2.t=100;
mtGeneric2.show(510);
String string=myGeneric2.getT();
}
}
泛型接口
/**
*注意:不能泛型静态常量
*
*/
public interface MyInterface<T>{
String name="张三";
T server(T t);
}
//1. 确定类型
public class MyInterfaceImpl implements MyInterface<String>{
@override
public String server(Sting t){
// TODO Auto-generated method stub
System.out.println(t);
return null;
}
}
//2. 不确定类型
public class MyInterfaceImpl2<T> implements MyInterface<T>{
@override
public String server(Sting t){
System.out.println(t);
return null;
}
}
public class TestInterface{
MyInterfaceImpl impl=new MyInterfaceImpl();
impl.server("xxxxx");
MyInterfaceImpl2<Interger> impl2=new MyInterfaceImpl2<>();
impl.server(1000);
}
泛型方法
/**
* 语法:<T> 返回值类型
*/
public class MyGenericMethod{
//泛型方法
public <T> T show(T t){
System.out.println("泛型方法"+t);
return t;
}
}
public class TestInterface{
MyInterfaceImpl2<Interger> impl2=new MyInterfaceImpl2<>();
impl.server(1000);
MyGenericMethod myGenericMethod=new MyGenericMethod();
myGenericMethod.show("abcd");
}
泛型好处
1)提高代码的重用性;(不用泛型,会使用方法重载)
2)防止类型转换异常,提高代码的安全性。
泛型集合
概念:参数化类型,类型安全的集合,强制集合元素的类型必须一致。
特点:
编译时即可检查,而非运行时抛出异常;
访问时,
public class Demo2{
public static void main(String args){
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add('xxx');
arrayList.add('xxx');
arrayList.add(123);//此时泛型为String,添加Integer会报错
arrayList.add(345);//
for(Object obj:arrayList){
String s=(String) obj;//若不适用泛型,则会出现强制错误
System.out.println(s);
}
ArrayList<Student> arrayList=new ArrayList<Student>();
Student s1=new Student("曹",14);
Student s2=new Student("曹",14);
arrayList.add(s1);
arrayList.add(s1);
for(Student stu:arrayList){
System.out.println(stu.toString());
}
Iterator<Student> it=arrayList.iterator();
while(it.hasNext()){
Student s=it.next();
System.out.println(s.toString());
}
}
}