问题:
1、什么是泛型和泛型的好处
2、泛型在集合中的应用
3、泛型在函数上的应用
4、泛型在类上的应用
5、泛型在接口上的应用
1、什么是泛型和泛型的好处
1、范型:JDK1.5版本以后出现新特性,用于解决安全问题,是一个类型安全机制
好处:
1、将运行时期出现问题classcastexception,转移到了编译时期,方便于程序员解决问题,让运行时期问题减少,安全
2、避免了强制转换麻烦
2、泛型在集合中的应用
正确的书写,后面2种是为了兼容新老系统
ArrayList<String> list = new ArrayList<String>();
ArrayList list = new ArrayList<String>();
ArrayList<String> list = new ArrayList();
错误的书写,两边的数据类型必须一致
ArrayList<Object> list = new ArrayList<String>();
ArrayList<String> list = new ArrayList<Object>();
注意: 在泛型中没有多态的概念,两边的数据必须要一致。 或者是只写一边 的泛型类型。
推荐使用: 两边的数据类型都写上一致的。
集合样例
package cn.xlucas.genecity;
import java.util.ArrayList;
public class GenecityDemo1 {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>();
list.add("abc");
list.add("cdr");
list.add("frg");
//list.add(123); 加了泛型以后编译就会出错了
//如果没有加泛型,那么运行的是就会抛出这个异常classcastexception
for(int i=0;i<list.size();i++){
String str=list.get(i);
System.out.println(str.toUpperCase());
}
}
}
3、泛型在函数上的应用
自定义泛型: 自定义泛型可以理解为是一个数据类型的占位符,或者是理解为是一个数据类型的变量。
泛型方法:
泛型方法的定义格式:
修饰符 <声明自定义泛型>返回值类型 函数名(形参列表..){
}
注意:
1. 在方法上的自定义泛型的具体数据类型是调用该方法的时候传入实参的时候确定的。
2. 自定义泛型使用的标识符只要符合标识符的命名规则即可。
泛型在函数上应用的案例
package cn.xlucas.genecity;
/*
*需求: 定义一个函数可以接收任意类型的参数,要求函数的返回值类型与实参的数据类型要一致。
*/
public class GenecityDemo2 {
public static void main(String[] args) {
Integer i=toprint(123);//这个传入的类型是Integer类型返回的也是Integer类型
String str=toprint("123");//这个传入的类型是String类型返回的也是String类型
}
public static <T> T toprint(T t){
return t;
}
}
4、泛型在类中的应用
泛型类的定义格式:
class 类名<声明自定义的泛型>{
}
注意的事项:
1. 在类上自定义的泛型的具体数据类型是在创建对象的时候指定的。
2. 在类上自定义了泛型,如果创建该类的对象时没有指定泛型的具体类型,那么默认是Object类型。
泛型在类中的使用案例
package cn.xlucas.genecity;
class MyList<T>{
Object[] arr=new Object[10];
int index=0;
public void add(T o){
arr[index++]=o;
}
}
public class GenecityDemo3 {
public static void main(String[] args) {
MyList<String> ls=new MyList<String>();
ls.add("abc");
MyList<Integer> lss=new MyList<Integer>();
lss.add(11);
//The method add(Integer) in the type MyList<Integer> is not applicable
//for the arguments (String)
}
}
5、泛型在接口中的应用
泛型接口的定义格式:
interface 接口名<声明自定义的泛型>{
}
在接口上自定义泛型要注意的事项:
1. 在接口上自定义泛型的具体数据类型是在实现该接口的时候指定的。
2. 如果一个接口自定义了泛型,在实现该接口的时候没有指定具体的数据类型,那么默认是Object数据类型。
如果想在创建接口实现类对象的时候再指定接口自定义泛型 的具体数据类型?
泛型在接口中的使用案例,在实例化的时候在指定类型
package cn.xlucas.genecity;
interface Dao<T>{
public void add(T t);
public void remove(T t);
}
public class GenecityDemo4<T> implements Dao<T> {
public static void main(String[] args) {
new GenecityDemo4<String>();
}
@Override
public void add(T t) {
}
@Override
public void remove(T t) {
}
}
泛型在接口中使用,在实现该接口的时候如果指定了泛型的类型,那么实现的方法类型也应该一样
package cn.xlucas.genecity;
interface Dao<T>{
public void add(T t);
public void remove(T t);
}
public class GenecityDemo4 implements Dao<String> {
public static void main(String[] args) {
}
@Override
public void add(String t) {
}
@Override
public void remove(String t) {
}
}