Set集合基本操作方法

package com.wy.test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetTest {
    public static void main(String[] args) {
        Set<String> set = new HashSet();

        //1.增加元素
        set.add("001");
        set.add("002");
        set.add("003");
        set.add("004");
        set.add("005");
        System.out.println(set);
        System.out.println("----------------------");

        //元素数量
        int num = set.size();
        System.out.println(num);
        System.out.println("----------------------");

        //元素删除
        set.remove("002");
        System.out.println(set);
        System.out.println("----------------------");

        //使用迭代器遍历
        Iterator it = set.iterator();
        while (it.hasNext()){
            Object item = it.next();
            String s = (String)item;//强制转换
            System.out.println(s);
        }
        System.out.println("----------------------");

        //元素全部删除
        set.clear();
        System.out.println(set);
        System.out.println("----------------------");

        //判断集合是否为空
        boolean b = set.isEmpty();
        System.out.println(b);

    }
}

输出结果

[001, 002, 003, 004, 005]
----------------------
5
----------------------
[001, 003, 004, 005]
----------------------
001
003
004
005
----------------------
[]
----------------------
true

猜你喜欢

转载自www.cnblogs.com/gc56-db/p/9837479.html