集合。 随笔

Collection集合。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 java.util.Collection 接口。 没有索引

是所有单列集合的最顶层的接口,里面定义了所有单列集合共性的方法。

任意的单列集合都可以使用Collecion接口中的方法。

共性的方法:

............................

Iterrator接口

java.util.Iterator

迭代器,Collection集合元素的通用取出方式。对集合遍历。  也是有泛型的,跟着集合走

常用方法: boolean hasNext()  还有没有元素可以迭代。

      next()取出集合的下一个元素。

获取实现类的方式比较特殊:

在Collection接口中有一个方法叫 Iterator,这个方法的返回就是迭代器的实现类对象。

使用步骤:重点

1、使用集合中的方法,Iterator()获取迭代器的实现类对象,使用Iterator接口接收(多态)

2、使用hasnext方法,判断是否还有下一个

3、使用next,取出下一个元素

代码实现:

 public static void main(String[] args) {
        Collection<String> collection=new ArrayList<>();
        collection.add("科比");
        collection.add("姚明");
        collection.add("乔丹");
       Iterator<String> iterator =collection.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

Java的foreach:

内部也是迭代器,简化迭代器的使用:

public static void main(String[] args) {
        int[] arr={1,2,3,4};
        for(int i : arr){
            System.out.println(i);
        }
    }

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄