← 返回首页
JavaSE系列教程(四十一)
发表时间:2020-01-31 15:17:42
讲解Java集合框架之Set常用方法

Set常用方法如下:

方法名字 说明
size() 获取集合的长度
add(Object obj) 添加元素
remove(Object obj) 删除元素
contains(Object obj) 判断是否包含指定的元素
containsAll(Collection c) 判断是否包含指定的集合
clear() 清除所有元素
isEmpty() 判断集合是否为空
toArray() 转换为对象数组

通过一个实例理解以上所有方法:

        Set set = new HashSet();


        set.add("grape");
        set.add("banana");
        set.add("apple");
        set.add("orange");
        set.add(null);
        set.add("watermelon");
        set.add("apple");
        System.out.println(set.size()); 
        System.out.println("--------遍历所有元素----------");

        Iterator it = set.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }

        System.out.println("---------删除'orange'元素之后---------");

        set.remove("orange");
        it = set.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }


        Object[] arr = set.toArray();
        System.out.println("----------遍历对象数组-----------");
        for(Object obj: arr){
            System.out.println(obj);
        }

        System.out.println(set.contains("apple"));

        System.out.println(set.containsAll(Arrays.asList(new String[]{"apple", "grape", "watermelon"})));

        set.clear();

        System.out.println(set.isEmpty());

运行结果:
6
--------遍历所有元素----------
banana
orange
null
apple
grape
watermelon
---------删除'orange'元素之后---------
banana
null
apple
grape
watermelon
----------遍历对象数组-----------
banana
null
apple
grape
watermelon
true
true
true