Collection的使用(1)(用集合存储字符串)

编程入门 行业动态 更新时间:2024-10-27 14:28:20

Collection的使用(1)(用集合存储<a href=https://www.elefans.com/category/jswz/34/1771434.html style=字符串)"/>

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)(用集合存储字符串)

本文发布于:2024-02-25 20:15:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1700166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Collection

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!