Collection集合和迭代器的使用方法

集合

Collection是个集合
继承自Iterable,有构造方法,可以构造Arraylist集合对象

Collection<String> c=new ArrayList<String>();

add方法,会返回一个boolean类型true

 c.add("");

remove方法,用于删除集合中的元素,可以返回一个boolean类型(true或者false)

 c.remove("");

clear方法可以清空集合中的元素

 c.clear();

isEmpty方法:判断这个集合中是否为空,该方法返回一个boolean类型

c.isEmpty()

contains方法,判断这个集合中是否有该元素,该方法返回一个boolean类型

c.contains("xxx")

terator(迭代器)

使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection实现。

实现方法:

Iterator<String> it =list.iterator();

hasNext()方法:如果迭代器中还有下一个元素,返回true

it.hasNext()

next()方法,返回迭代集合的下一个元素

it.next()

或者输出

扫描二维码关注公众号,回复: 13115116 查看本文章
System.out.println(it.next());

迭代器的遍历方法‘

while (it.hasNext()){
            System.out.println(it.next());        
        }

猜你喜欢

转载自blog.csdn.net/Along_Dragon_/article/details/115353569
今日推荐