Java基础学习-泛型概述和测试

1.举例

首先先用集合来写个自定义对象存储并且去遍历。

package genericity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


public class genericity {
    public static void main(String[] args) {
        /*创建集合对象*/
        Collection ce=new ArrayList();
        /*创建学生类对象*/
        Student st1=new Student("bai-boy", 19);
        Student st2=new Student("xiaoming", 20);
        /*集合中添加元素*/
        ce.add(st1);
        ce.add(st2);
        /*遍历集合*/
        Iterator it=ce.iterator();
        while(it.hasNext()) {
            String str=(String)it.next();
            System.out.println(it);
        }
        
    }
}
class Student{
    String name;
    int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

但是运行会报错。

这个错误呢是由于创建的Student对象不能转化为String。那么我们这里Java给我们一个机制就是泛型

泛型:是一种广泛的类型,它把明确数据类型的工作提前到了编译时期而不是运行时期。

这里主要借鉴了数组。数组都是提前明确数据类型,不是同一的数据类型就不能添加进去。

那么我们什么时候使用泛型呢,打开API查看带有<E>就可以使用泛型了。

那我们用泛型来解决上面的问题

package genericity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


public class genericity {
    public static void main(String[] args) {
        /*创建集合对象*/
        Collection<Student> ce=new ArrayList<Student>();
        /*创建学生类对象*/
        Student st1=new Student("bai-boy", 19);
        Student st2=new Student("xiaoming", 20);
        /*集合中添加元素*/
        ce.add(st1);
        ce.add(st2);
        /*遍历集合*/
        Iterator<Student> it=ce.iterator();
        while(it.hasNext()) {
            Student st=it.next();
            System.out.println("我叫"+st.name+",年龄:"+st.age);
        }
        
    }
}
class Student{
    String name;
    int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

以上就是泛型的概述和简单的使用。

猜你喜欢

转载自www.cnblogs.com/bai-boy/p/10328785.html