Collection集合框架

集合是一种容器,可以存放不同的数据

记述一下这几天学的集合接口Collection,它有两个子接口,list和set。然而今天的主角不是他们,先写几个关于Collection的内容

  1. toAarray() 集合转数组
 public static void fun(){
        //转化成String数组
        Collection<String> as=new ArrayList<String>();
        as.add("海子");
        as.add("食指");
        as.add("春");
        //使用toArray无参方法,将元素赋值给Object数组array
        Object[] array=as.toArray();
        for (int i = 0; i <array.length ; i++) {
            System.out.println(array[i]);
        }
    }

显示结果:

海子
食指
春
  1. contains() 判断字符 是否存在
public static void fun1(){
        Collection<String> co=new ArrayList<String>();
        co.add("a");
        co.add("b");
        co.add("c");
        co.add("d");
        boolean s=co.contains("a");
        System.out.println(s);
    }

显示结果:

true
  1. clear() 清除集合中的元素 但是集合本身并没有被清除,还存在
//清除集合中元素  集合本身并不清除
    public static void fun2(){
        Collection<String> coll=new ArrayList<String>();
        coll.add("qy97");
        coll.add("qu95");
        System.out.println(coll);
        coll.clear();
        System.out.println(coll);
    }

显示结果:

[qy97, qu95]
[]

有集合就避免不了对数据元素的遍历,下面介绍一下集合通用的遍历

  1. 迭代器
    迭代器 是一种遍历集合元素的方法,通过iterator()方法,获得迭代器
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo2 {
    public static void main(String[] args) {
            Collection<String> co = new ArrayList<String>();
            co.add("我爱");
            co.add("我家");
            //通过iterator()方法,获得迭代器
            Iterator<String> it = co.iterator();
            //判断集合中对象是否有下一个元素,没有返回false
            while (it.hasNext()) {
            	//获取下个元素
                String s = (String) it.next();
                System.out.println(s);
            }
    }
}

显示结果:

我爱
我家

注意:在使用迭代器时,不能向集合中添加或删除元素,否则抛出异常

Exception in thread "main" java.util.ConcurrentModificationException

此处不再具体举例

  1. 增强型for循环 没有索引,直接对集合中元素操作
    for(数据类型 变量名:集合或者数组){
    代码块
    }
public class ForEach {
    public static void main(String[] args){
            int[] arr={13,64,63,65,6,2};
            //增强型for循环  没有索引 直接对集合中元素操作
            for(int i:arr){
                //所有元素的值都加1
                System.out.println(i+1);
            }
            //输出元素下表为0的元素
            System.out.println(arr[0]);
    }
}

显示结果:

14
65
64
66
7

增强型for循环里面使用迭代器,所以也会有抛出异常的现象,即不能在使用迭代器时,向集合中添加或者删除元素
下一篇会具体举例 怀着一颗谦虚的心

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值