Java基础-集合(1)----- collection

public static void main(String[] args) {
  	Collection c1 = new ArrayList();
  	Collection c2 = new ArrayList();
  	
  	//添加 
  	c1.add(555);//1.添加一个元素
  	c1.add(666);
  	c1.add(777);
  	c1.add("abc");
  	c1.add("xyz");
  	c2.addAll(c1);//2.添加一个集合的元素
  	System.out.println(c2);  
 
 	 //删除
  	c1.clear();//1.移除所有的元素
  	boolean b1 = c2.remove(555);//2.移除一个元素
  	System.out.print(c2);
  	System.out.println(" remove555 "+b1);
  	//3.移除一个集合的元素,只要一个元素被移除了,就返回true
  	boolean b2 = c2.removeAll(c2);
  	System.out.println(c2+" removeAll "+b2);  
 	
 	 //判断  
  	Collection c3 = new ArrayList();
  	c3.add(555);
  	c3.add("abc");
  	c3.add("yyy");
  	//1.判断集合是否包含该元素
  	boolean b3 = c3.contains(555);
  	//2.判断集合中是否包含指定的集合元素
  	boolean b4 = c3.containsAll(c2);
  	System.out.println("contains "+b3);
  	System.out.println("containsAll "+b4);
 	 //3.判断集合是否为空
  	boolean b5 = c2.isEmpty();
  	System.out.println("isEmpty " + b5);
  	
  	//迭代器 (遍历集合)
        /*
	 * Iterator有三个方法:hasnext()、next()、remove()、
	 * hasnext()没有指针下移,只是判断是否存在下一个元素
	 * next()指针下移,返回该指针指向的元素
	 * remove删除当前指针指向的元素,一般和next方法一起用,
         * 其作用是删除next方法返回的元素
         */ 
	Iterator it = c3.iterator();
	//1.while遍历
  	System.out.println("---两种遍历---");
 	while(it.hasNext()) {
		Object obj = it.next();
       		System.out.print(obj + " ");
       		if(obj.equals(555)) {
    			it.remove();//删除
      		 }
 	 }System.out.println();
  
  	//2.增强for
  	for (Object obj : c3) {
   		System.out.print(obj + " ");   
 	}System.out.println();
  
  	//交集
  	//1.将两个集合的交集给c1,返回值表示c1是否变化
  	boolean b6  = c1.retainAll(c3);
  	System.out.println("retainAll " + b6);
  	System.out.println("c1 " + c1);
  	System.out.println("c3 " + c3);       
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值