collection常用功能:

collection常用功能:

Collection是所有单列集合的父接口,因此在collection中定义了单列集合(List)和(Set)通用的一些方法。这些方法可用于操作所有的单列集合,方法如下:

1)public boolean addE e:把给定的对象添加到当前集合中

2)Public void clear():清空集合中所有的对元素

3)Public boolean removeE e):把给定 对象在集合中移除

4)Public boolean containsE e:判断当前集合中是否包含给定的对象

5)Pulbic boolean isEmpty():判断当前集合是否为空

6)Public int size():返回集合中元素的个数

7)Public object【】 toArray():把集合中的元素,存储到数组中

 

 

package com.ithima.demo01.Object.Collection08;
/*
java.utill.collection接口
所有单列集合的最顶层的接口,里面定义了所有单 列集合的共性的方法
任意的单列集合都可以使用collection接口中的方法

共性的方法:
Collection是所有单列集合的父接口,因此在collection中定义了单列集合(List)和(Set)通用的一些方法。这些方法可用于操作所有的单列集合,方法如下:
1)public boolean add(E e):把给定的对象添加到当前集合中
2)Public void clear():清空集合中所有的对元素
3)Public boolean remove(E e):把给定 对象在集合中移除
4)Public boolean contains(E e):判断当前集合中是否包含给定的对象
5)Pulbic boolean isEmpty():判断当前集合是否为空
6)Public int size():返回集合中元素的个数
7)Public object【】 toArray():把集合中的元素,存储到数组中

*/


import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;

public class demo02Collection {
    public static void main(String[] args) {
        //首先要创建集合对象,可以使用多态
        Collection<String> coll = new ArrayList<>();
        System.out.println(coll);//[] 打印了空列表,没有打印地址,说明重写了toString方法
/*
        1)public boolean add(E e):把给定的对象添加到当前集合中
        返回的是布尔值,一般都返回true,所以可以不用接收
*/

        boolean b1 = coll.add("张三");//
        System.out.println("b1:" + b1); //true一般不用接收,没有意思
        System.out.println(coll);
        coll.add("李四");
        coll.add("hello");
        coll.add("王五");
        System.out.println(coll); //[张三, 李四, hello, 王五]


/*
        3)Public boolean remove(E e):把给定 对象在集合中移除
        返回值是布尔值,集合中存在元素,删除元素,返回true,集合中不存在元素,删除失败,返回false

*/
        boolean b2 =  coll.remove("王五");
        System.out.println("b2 :"+   b2);
        System.out.println(coll);

        boolean b3 = coll.remove("赵六"); //集合中不存在
        System.out.println("b3:" + b3);
        System.out.println(coll);

/*
        4)Public boolean contains(E e):判断当前集合中是否包含给定的对象
            包含返回true
            不包含返回false
*/
        boolean b4 = coll.contains("李四");
        System.out.println("b4;" + b4);  //true

        boolean b5 = coll.contains("上宫四");
        System.out.println("b5 : " + b5);//false


/*
        5)Pulbic boolean isEmpty():判断当前集合是否为空
*/
        boolean b6 = coll.isEmpty();
        System.out.println("b6 : " + b6);
/*
        6)Public int size():返回集合中元素的个数

*/
        int size = coll.size();
        System.out.println("size : " +size);

/*
        7)Public object【】 toArray():把集合中的元素,存储到数组中
*/
        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

/*
        2)Public void clear():清空集合中所有的对元素
*/
        coll.clear();
        System.out.println(coll);
        System.out.println(coll.isEmpty());
    }
}

 

posted @ 2020-12-04 11:51  liujuan2728  阅读(186)  评论(0编辑  收藏  举报