字符串)"/>
Collection的使用(1)(用集合存储字符串)
Collection的使用(用集合存储字符串)
Collection是一个接口,通过实现类来创建对象
1.常用方法有add()、remove()、clear()、contains()、isEmpty()
add(Object o):给集合添加该元素
remove(Object o):给集合移除该元素
clear():清空集合所有元素
contains(Object o):判断集合中是否有该元素
isEmpty():判断该集合是否为空
2.迭代器(重点)
Iterator是一个接口,该接口有以下方法:hasNext(),next(),remove(),通过Collection接口的iterator()方法创建对象
注意:在使用迭代期迭代的过程中,不能使用Collection的方法改变集合元素,因为迭代器在操作集合此时不能对集合修改,否则会出现并发修改异常ConcurrentModificationException
public class Test {public static void main(String[] args) {//创建集合Collection collection = new ArrayList();collection.add("西瓜");collection.add("榴莲");collection.add("苹果");//删除collection.remove("榴莲");//输出个数int size = collection.size();System.out.println(size);//2System.out.println(collection);//[西瓜, 苹果]//清空//collection.clear();//System.out.println(collection.size());//2//System.out.println(collection);// []//遍历//1.增强for循环System.out.println("====================增强for循环===========================");for(Object object:collection ){System.out.println(object);}//迭代器(专门用来遍历集合的一种方式)//hasNext():有没有下一个元素//next():获取下一个元素//remove():删除下一个元素System.out.println("====================迭代器遍历==========================");Iterator iterator = collection.iterator();while (iterator.hasNext()){String next = (String)iterator.next();// collection.remove(next);//迭代器在迭代过程中不允许使用collection的一些方法改变元素,否则会导致并发修改异常//ConcurrentModificationExceptioniterator.remove();//迭代过程中移除元素System.out.println(next);}System.out.println("遍历移除后的个数:"+collection.size());//遍历移除后的个数:0//判断:(contains()、isEmpty())System.out.println(collection.contains("西瓜"));//falseSystem.out.println(collection.isEmpty());//true}
}
更多推荐
Collection的使用(1)(用集合存储字符串)
发布评论