HashSet的常用方法

发布时间 2023-10-01 17:53:25作者: 顺风顺水heng
public static void main(String[] args) {

    HashSet set = new HashSet<>();

    //添加元素
    set.add("hao");
    set.add("shuai");

    //删除元素
    set.remove("hao");

    //判断是否包含某元素
    if (set.contains("shuai")){
        System.out.println("包含");
    }else {
        System.out.println("不包含");
    }

    //判断集合是否为空
    if (set.isEmpty()){
        System.out.println("为空");
    }else {
        System.out.println("不为空");
    }


    //获取迭代器
    Iterator<String> i = set.iterator();
    while (i.hasNext()){
        String s  = i.next();
        System.out.println(s);
    }

    //清空所有元素
    set.clear();
    if (set.isEmpty()){
        System.out.println("为空");
    }else {
        System.out.println("不为空");
    }

}