泛型入门

泛型:
自我理解是一种提前明确并规定数据类型的一种方法。
用代码可以直观的表示出泛型的基本用法:

public static void main(String[] args) {
        //创建一个集合
//      ArrayList al = new ArrayList();
//      al.add("hello");
//      al.add("world");
//      al.add("java");
//      al.add(100);

        //创建ArrayList集合的时候就给集合加上泛型,明确一下这个的类型
        //在这里已经明确了数据类型,说明目前只能给al集合中添加String类型的元素
        ArrayList<String> al = new ArrayList<String>();
        al.add("java");
        al.add("hello");
        al.add("world");
        //al.add(100);  报错!

泛型也可以指定自定义对象。

public static void main(String[] args) {
        //创建集合对象并加上泛型

        //创建学生对象
        Student s = new Student("a", 11);
        Student s1 = new Student("b", 22);
        Student s2 = new Student("c", 33);

        //创建集合对象并加上泛型
        List<Student> list = new ArrayList<Student>();

        //集合中添加元素
        list.add(s);
        list.add(s1);
        list.add(s2);

        //使用迭代器进行遍历
        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            //取出迭代器中的元素
            Student ss = it.next();
            System.out.println(ss.getAge()+"  "+ss.getName());
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值