Java泛型集合介绍

为集合设置通用类型

可以为Java Collections API中的大多数组件指定通用类型

为Java集合设置通用类型时,需要在声明引用它的变量时进行设置
Collection<String> stringCollection=new HashSet<>();

现在,此stringCollection只能包含String实例。 如果您尝试添加其他任何内容,或将集合中的元素强制转换为String以外的任何其他类型,则编译器会报错

You can specify a generic type for a List’s, Set’s etc.

Generic iterator

为Java集合指定通用类型后,该通用类型也适用于iterator()方法返回的Iterator。 这是一个如何获取设置了通用类型的Iterator的示例:

        Collection<String> stringCollection = new HashSet<>();
        stringCollection.add("eason");
        stringCollection.add("vae");
        stringCollection.add("Trump");

        Iterator<String> iterator = stringCollection.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

it is not necessary to cast the String returned from the iterator.next() method call. Because the Iterator has its generic type set to String, the Java compiler already knows that next() will return a String.

Generic Iteration Using for Loop

        Collection<String> stringCollection = new HashSet<>();
        stringCollection.add("eason");
        stringCollection.add("vae");
        stringCollection.add("Trump");


        for (String element : stringCollection) {
            System.out.println(element);
        }

Notice how it is possible to specify the type of the variable of each element (stringElement) as String. This is possible because the generic type of the Collection is set to String.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值