HashSet的使用(1)

package com.sean.base.SetStudy;

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

/**
 * HashSet集合的使用
 * 存储结构:哈希表(数组+链表+红黑树)
 *
 * @create 2021-02-25 14:29
 */
public class Demo02 {
    public static void main(String[] args) {
        //新建集合
        HashSet<String> hashSet = new HashSet<String>();
        //1添加元素
        hashSet.add("刘德华") ;
        hashSet.add("张荣华") ;
        hashSet.add("大张伟") ;
        hashSet.add("东东") ;
        System.out.println("元素个数:"+hashSet.size());
        System.out.println(hashSet.toString());

        //2删除
        /*hashSet.remove("刘德华");
        System.out.println("删除之后:"+hashSet.size());*/

        //3遍历
        //3.1使用增强for
        System.out.println("-----------3.1使用增强for---------");
        for (String string:hashSet
        ) {
            System.out.println(string);

        }
        //3.2使用迭代器
        System.out.println("-----------3.2使用迭代器---------");
        Iterator<String> it=hashSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //4判断
        System.out.println(hashSet.contains("小米"));
        System.out.println(hashSet.isEmpty());

    }
}

 

posted @ 2021-02-25 14:43  之樾  阅读(87)  评论(0)    收藏  举报