泛型(泛化类型)
泛型就相当于我们容器上的标签,表明容器的内容是什么
**
* 泛型的入门 <>
* 1、泛型: 标签 ,泛化类型
* 2、作用: 省心 安全
*/
public class Simple {
public static void main(String[] args) {
List<String> list =new ArrayList<String>();
//List<Integer>
//安全
//list.add(1); //类型检查
list.add("so easy");
//省心
String ele =list.get(0);
System.out.println(ele);
//jdk1.4之前
List list2 =new ArrayList();
list2.add(1);
list2.add("old");
//取出数据
Object obj =list2.get(0);
//麻烦
Integer num =(Integer)obj;
//不安全
//num =(Integer)list2.get(1);
if(list2.get(1) instanceof Integer){ //手动类型检查
num =(Integer)list2.get(1);//手动类型转换 才能安全
}
}
}
- 泛型类
/**
* POJO类 JAVABean
*/
public class Student {
//成绩
private Object javase;
public Student() {
}
public Student(Object javase) {
this.javase =javase;
}
public Object getJavase() {
return javase;
}
public void setJavase(Object javase) {
this.javase = javase;
}
}
/**
* 没有泛型的类 存储数据-->麻烦
* @author bj
*/
public class StuApp {
public static void main(String[] args) {
//存入整数 int -->Integer -->Object
Student stu = new Student(80);
Object javase =stu.getJavase();
//类型检查 处理转换异常
if(javase instanceof Integer){
//强制类型转换
Integer javaseScore =(Integer) javase ;
}
stu =new Student("优秀");
javase =stu.getJavase();
//类型检查 处理转换异常
if(javase instanceof String){
//强制类型转换
String javaseScore =(String) javase ;
}
}
}
public class Student<T> {
//成绩
private T javase;
public Student() {
}
public Student(T javase) {
this.javase =javase;
}
public T getJavase() {
return javase;
}
public void setJavase(T javase) {
this.javase = javase;
}
}
/**
* 自定义泛型类的使用,
* 在声明时指定具体的类型,
* 不能为基本类型
*/
public class MyStuApp {
public static void main(String[] args) {
//MyStudent<int> stu =new MyStudent<int>();不能为基本类型
MyStudent<Integer> stu =new MyStudent<Integer>();
//1、安全:类型检查
//stu.setJavase("优秀");
stu.setJavase(80);
//2、省心:自动类型转换,免去了类型检查
Integer score=stu.getJavase();
System.out.println(score);
}
}
- 泛型接口
/**
* 泛型接口
* 泛型不能使用在全局常量上
* @param <T>
*/
public interface Comparator<T> {
//全局常量
/*public static final*/ int MAX_VALUE=1024;
//公共的抽象方法
/*public abstract */T compare(T t);
}
- 泛型方法,擦除,嵌套
/**
* 非泛型类中 定义泛型方法
* 定义: 在返回类型前面加<字母>
* @author bj
*
*/
public class Method {
//泛型方法
public static <T> void test(T t){
System.out.println(t);
}
public static <T extends List> void test(T t){
System.out.println(t);
t.add("aaa");
}
//释放资源
public static <T extends Closeable> void test(T... a){
for(T temp:a){
try {
if(null!=temp){
temp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws FileNotFoundException {
test("bjsxt is very good");
test(new FileInputStream("a.txt"));
}
}
总结
泛型概念:<> 泛化类型
泛型作用:安全 省心
自定义泛型
泛型类: 类<字母,…> T E K V
只能用在成员变量上 只能使用引用类型泛型接口: 接口<字母,…>
只能用在抽象方法上泛型方法: <字母,..> 返回类型|void