Java_基础—HashSet存储字符串并遍历

package com.soar.set;

import java.util.HashSet;

public class Demo1_HashSet {
/*
 * set集合,无索引,不可以重复,存取不一致(无序)
 */
    public static void main(String[] args) {
        HashSet<String> hs = new HashSet<>();       //创建HashSet对象
        boolean b1 = hs.add("a");
        boolean b2 = hs.add("a");       //当向set集合中存储重复元素的时候,返回为false
        System.out.println(hs);         //[a]   HashSet继承体系中有重写toString方法
        System.out.println(b1);         //true
        System.out.println(b2);         //false

        hs.add("b");
        hs.add("c");
        hs.add("d");
        System.out.println(hs);     //[d, b, c, a] 无序

        for (String string : hs) {          //只要能用迭代器迭代的,就可以使用增强for循环遍历
            System.out.println(string);     //d,b,c,a 
        }
    }

}
posted @ 2017-07-15 09:02  Soar_Sir  阅读(746)  评论(0编辑  收藏  举报