Collection集合接口

Collection集合
Collection集合接口是所有集合的顶级接口

注意:集合存储只能是对象,要存储基本数据类型,要用到其基本的数据类型对应的包装类

ArrayList arrayList = new ArrayList<>();

ArrayList arrayList = new ArrayList<>();

Collection集合的框架

java.util.Collection接口

所有单列集合的最顶层的接口,里面定义了所有单列集合共性的方法

任意的单列集合都可以使用Collection接口中的方法

共性方法

boolean add(E e);//往集合中添加指定的元素
void clear();//清空集合中的所有元素,集合还存在,只是集合中没有元素
boolean remove(Object o);//删除集合中的指定元素
boolean containsAll(Collection<?> c)//判断集合中是否包含指定元素
boolean isEmpty();//判断集合是否为空
int size();//判断集合的长度
 Object[] toArray();//将集合转化为数组

package commonclass;
//测试collection中的常用方法
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class TestCollection01 {
    public static void main(String[] args) {
        //创建一个集合对象,接口引用指向实现子类(多态)
        Collection<String> arrayList = new ArrayList<>();
        System.out.println(arrayList);

        arrayList.add("abc");//返回值一般为true,一般不用接收
        arrayList.add("def");
        arrayList.add("hij");
        System.out.println(arrayList);//[abc, def, hij]


        boolean b1 = arrayList.remove("hij");
        System.out.println(b1);//true
        boolean b2 = arrayList.remove("mmm");//集合中不包含“mmm”,删除失败,返回false
        System.out.println(b2);//false
        System.out.println(arrayList);//[abc, def]

        boolean b3 = arrayList.contains("abc");
        System.out.println(b3);//true
        boolean b4 = arrayList.contains("abd");
        System.out.println(b4);//false

        boolean empty = arrayList.isEmpty();
        System.out.println(empty);//false

        int size = arrayList.size();
        System.out.println(size);//2

        Object[] objects = arrayList.toArray();
        System.out.println(Arrays.toString(objects));//[abc, def]

        arrayList.clear();
        System.out.println(arrayList.size());//0
        System.out.println(arrayList);//[]


    }
}
posted @ 2020-08-09 18:52  DannyBoy~  阅读(168)  评论(0)    收藏  举报