Java集合小结(1)

1.Collection类

     Collection 接口是 ListSet父接口,该接口里定义的方法既可用于操作Set集合 和List集合,常用的方法有如下:

      (1) 添加元素

           add()

           addAll()

      (2)移除元素

           通过equals( )判断集合中是否存在对应的元素

            remove()

            removeAll()

            clear( )

          (3)检测集合中的元素

                  contains()

            containsAll()

            equals()

      (4)遍历集合中的元素

            literator()

       (5)转化为对应的数组

            toArray( )

         

package com.exception;

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

public class TestCollection {

	public static void main(String[] args) {
	// 添加元素
	//add(),addAll()
		Collection c= new ArrayList ();
		People p1 =new People();
		People p2 =new People();
		c.add( p1);
		c.add( p2);
		Collection c1= new ArrayList ();
		People p3 =new People();
		c1.add( p1);
		c1.add( p2);
	 
		 
System.out.println(c.size());
		/**
		 * 访问元素:
		 * 1.获取迭代器
		 * 2.是否有下一个元素iterator.hasNext()
		 * 3.访问元素iterator.next()
		 * */
		Iterator  iterator=c.iterator();
		while(iterator.hasNext()){
			System.out.println(iterator.next());
		}
	 /**
	  * 移除元素:remove() :通过equals()判断是否存在
	  *          removeAll()
	  *          clear()
	  *          
	  * */
			
//			boolean b =c.remove( p1);
//			System.out.println(c.size());
//			System.out.println(c1.size());
//			c.removeAll(c1); 
//			System.out.println(b);
//			System.out.println(c.size());
			/**
			 * 检测集合中存在元素:
			 * contains();
			 * containsAll();
			 * equals();
			 * 
			 * */
        System.out.println(c.equals(c1));
		 System.out.println(c.contains(p1));
		 System.out.println(c.contains(new People()));
		 System.out.println(c.containsAll( c1));
	 //重要方法:toArray() 集合转化为相应的数组
		 Object[] obj= c.toArray();
		 System.out.println(obj.length);
		
	}
	
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值