Collection集合常用方法运行示例

boolean add(E e)

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

public class CollectionDemo_02 {
    public static void main(String[] args) {
         //创建集合对象
        Collection<String> c = new ArrayList<String>();

         //boolean add(E e):添加元素
        System.out.println(c.add("hello"));
        System.out.println(c.add("world"));
        System.out.println(c.add("world"));

        //输出集合对象
        System.out.println(c);
        /*
            运行结果:
                    true
                    true
                    true
                    [hello, world, world]
            为什么运行结果全为true呢? 通过查看源码后,add方法返回值永远是true.
            public boolean add(E e) {
                ensureCapacityInternal(size + 1);  // Increments modCount!!
                elementData[size++] = e;
                return true;
            }
         */
    }
}

 boolean remove(Object o)

public class CollectionDemo_02 {
    public static void main(String[] args) {
         //创建集合对象
        Collection<String> c = new ArrayList<String>();

         //boolean add(E e):添加元素
        c.add("hello");
        c.add("world");
        c.add("java");

        //boolean remove(Object o):从集合中移除指定的元素
        System.out.println(c.remove("world"));
        System.out.println(c.remove("javaee"));
        //输出集合对象
        System.out.println(c);
        
        /*
            运行结果:
                    true
                    false  集合中没有"javaee"元素,所以false
                    [hello, java] 成功删除元素"world"
         */

    }
}

void clear() :清空集合中的元素 (添加的元素在前面代码中)

//void clear() : 清空集合中的元素
        c.clear();
        //输出集合对象
        System.out.println(c);
        /*
            运行结果:
                    []
         */

boolean contains(Object o) :判断集合中是否存在指定的元素

//boolean contains(Object o):判断集合中是否存在指定的元素
        System.out.println(c.contains("world"));
        System.out.println(c.contains("javaee"));
        //输出集合对象
        System.out.println(c);

        /*
            运行结果:
                    true    //集合中存在元素world
                    false   //集合中没有元素javaee
                    [hello, world, java]
         */

boolean isEmpty():判断集合是否为空

//boolean isEmpty():判断集合是否为空
        System.out.println(c.isEmpty());
        System.out.println(c);
        c.clear();
        System.out.println(c.isEmpty());
        //输出集合对象
        System.out.println(c);

        /*
            运行结果:
                    false   // 不为空
                    [hello, world, java]
                    true
                    []

         */
int size() : 集合的长度,也就是集合中元素的个数

//int size() : 集合的长度,也就是集合中元素的个数
        System.out.println(c.size());
        //输出集合对象
        System.out.println(c);

        /*
            运行结果:
                    3
                    [hello, world, java]

         */
posted @ 2020-04-06 15:40  硬盘红了  阅读(176)  评论(0编辑  收藏  举报