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

来源:互联网 发布:javascript实战项目 编辑:程序博客网 时间:2024/06/14 08:35
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         }    }}
原创粉丝点击