Collection集合常用功能

78 阅读1分钟
  1. java.util.Collection接口:所有单列集合的最顶层的接口,里边定义了所有单列集合共性的方法,任意的单列集合都可以使用Collection接口中的方法,没有带索引的方法
  2. 共性方法:
   1. public boolean add(E e):把给定的对象添加到当前集合中
   2. public void clear():清空集合中所有的元素
   3. public boolean remove(E e):把给定的对象在当前集合中删除
   4. public boolean contains(E e):判断当前集合中是否包含给定对象
   5. public boolean isEmpty():判断当前集合是否为空
   6. public int size():返回集合中元素的个数
   7. public Object[] toArray():把集合中的元素,存储到数组中
  1. 实例展示:
package com.Java集合.Collection;

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

public class Test {

    public static void main(String[] args) {
        //创建集合对象,可以使用多态
        Collection<String> coll = new ArrayList<>();
        System.out.println(coll);//[]  -->重写了toString()方法

        System.out.println("--------add--------");

        coll.add("java");
        coll.add("is");
        coll.add("the");
        coll.add("best");
        coll.add("language");
        coll.add("!");
        System.out.println(coll);//[java, is, the, best, language, !]

        System.out.println("--------remove-----------");

        boolean b1 = coll.remove("!");
        System.out.println(coll);//[java, is, the, best, language]
        System.out.println(b1);//true

        boolean b2 = coll.remove(",");//原本集合里面就没有 ","  所以返回 false
        System.out.println(coll);//[java, is, the, best, language]
        System.out.println(b2);//false

        System.out.println("--------contains--------");
        boolean b3 = coll.contains("java");
        boolean b4 = coll.contains("!");
        System.out.println(b3);//true
        System.out.println(b4);//false

        System.out.println("-----------isEmpty-------------");
        boolean b5 = coll.isEmpty();
        System.out.println(b5);//false

        System.out.println("-----------size-------------");
        int in = coll.size();
        System.out.println(in);//5

        System.out.println("-----------toArray-------------");
        Object[] ob = coll.toArray();
        for (int i = 0; i < ob.length; i++) {
            System.out.println(ob[i]);
        }

        System.out.println("-----------clear-------------");
        coll.clear();
        boolean b6 = coll.isEmpty();
        System.out.println(b6);//true
    }

}