Collection 集合的练习

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

/**
 * Collection 集合的练习 (添加元素,删除元素,返回Collection集合的元素个数,清空整个集合)
 * @author yong718100
 *
 */

public class TestCollection {

    /**
     * @param args
     */
    public static void main(String[] args) {
   
        Collection c = new ArrayList();
        Collection collection = new ArrayList();
        c.add("周星驰");
        c.add("古巨基");
        c.add("刘德华");    //添加元素   (增)
        c.add("6");        //虽然集合里不能放基本类型的值,但Java支持自动装箱
        collection.addAll(c);   
        System.out.println("c集合的元素个数:" + c.size());
        c.remove(6);    //删除指定元素(删)
        System.out.println("c集合的元素个数:" + c.size());
        System.out.println("c集合的是否包括刘德华字符串:" + c.contains("刘德华"));//判断是否包含指定字符串
        c.add("成龙大哥");
        System.out.println("c集合的元素:" + c.toString());    //(查)toSrring();叔祖显示元素集合
        System.out.println("c集合是否为空:" + c.isEmpty());   
       
        Collection c2 = new HashSet();
        c2.add("周星驰");
        c2.add("古巨基");
        System.out.println("c集合是否完全包含c2? " + c.containsAll(c2));    ////判断是否包含指定集合
        c.removeAll(c2);        //用 c 集合减去 c2 集合里的元素
        System.out.println("c集合剩余的元素:" + c);
        c.clear();                //清空元素
        System.out.println("c集合剩余的元素:" + c);
        c2.retainAll(c);        //获得c2与c的交集
        System.out.println("c2集合的元素:" + c2);
       
        /**************************遍历集合的俩中方法:Iterator,foreach****************************/
        //1.使用Iterator接口遍历集合元素 hasNext(),next(),remove
        Iterator it = collection.iterator(); //返回在此Collection的元素上进行迭代的迭代器
       
        while (it.hasNext())    //如果仍有元素可迭代,则返回true
        {    //此string 不是集合本身
            String string = (String)it.next();    //返回当前元素,指针指向下一个元素
            System.out.println(string);   
           
            if (string.equals("古巨基"))
                it.remove();    //从集合中删除上一次next()方法返回的元素
            string = "测试字符串";    //对next()的返回值进行赋值,不会改变集合元素本身
//            collection.remove(string);    //使用Iterator迭代器过程中,不可修改集合元素,否则发生异常 ConcurrentModificationException
        }
        System.err.println(collection);   
       
        //2.使用foreach
        for (Object obj : collection)
        {    //此string 不是集合本身
            String string = (String)obj;
            System.out.println(string);
            if (string.equals("刘德华"))
            {
                collection.remove(string);    //会少输出一个结果
            }
            System.err.println(string);
        }
        System.err.println(collection);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值