集合

                                         集合

   前面我们介绍了数组的概念,集合和数组都可以被看错是一种容器,不过数组的长度是固定的,而集合是可以改变长度的,但是存放的元素必须是引用数据类型的元素,这也是和数组的几个区别

前面我们介绍过Arraylist集合,这里不再做赘述,今天我们看一下collection接口

    collection接口

次接口是一个顶层接口,他定义了许多功能和方法,子类都可以调用 

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Collection<String>coll=new ArrayList<String>();
        //add方法
        coll.add("1号");
        coll.add("2号");
        //集合转属组
        Object[] arr=coll.toArray();
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
        coll.remove("2号");//集合元素移除方法
        System.out.println(coll.size());
        boolean b=coll.contains("2号");//判断集合中是否有这个元素
        
        coll.clear();//清除得是你容器中的内容
    }

这是collection的集合转数组和添加删除元素的方法,在转数组的时候只能是Object类型的数组

迭代器

Iterator接口:它的主要作用是获取集合中的元素

public static void main(String[] args) {
        Collection<String>coll=new HashSet<String>();
        coll.add("小丫头");
        coll.add("你要好好学习");
        coll.add("你都这么大了");
        coll.add("还跟个小宝宝似得");
        //1.获得iterater对象
        //Iterator<String>it=coll.iterator();
//        while(it.hasNext()){
//            String str=it.next();
//            System.out.println(str);
//        }
        //System.out.println(it.hasNext());
        //System.out.println(it.next());
        for(Iterator<String>it=coll.iterator();it.hasNext();){
            System.out.println(it.next());
        }
    }

其中hasnext方法会返回一个布尔类型数据,判断一下集合中是否有元素,然后在遍历这个集合,这里介绍了两种方法,for 和while

猜你喜欢

转载自www.cnblogs.com/jingyukeng/p/8881498.html