Java集合基础篇(3)-HashSet基本用法

来源:互联网 发布:网络直播电视 编辑:程序博客网 时间:2024/06/03 17:08

HashSet实现Set接口。
Set是一个不包含重复元素的集合接口, 集合中的元素不按特定的方式排序。

  • 实现Set接口的类:
类 说明 使用场景 HashSet 无序、无重复元素 存取速度快 TreeSet 对够对集合对象进行排序 有序的Set。访问和检索速度快 LinkedHashSet 元素不允许有重复的, 但是是有序的, 其顺序和插入时一至 EnumSet CopyOnWriteArraySet 线程安全的。在进阶篇中详细讲解。

- HashSet用法:

(1) 定义HashSet

Set<String> set = new HashSet<>();//定义一个空的HashSet

(2) 添加元素
第一种方法: add()

set.add("hello");set.add("tom");set.add("hello");set.add("world");System.out.println(set);

由于set里面不能包含重复的元素。所以上面的程序执行结果为
[tom, world, hello]

第二种方法: addAll()

List<String> list = Arrays.asList("hello","world","hello");set.addAll(list);System.out.println(set);

执行结果为[hello,world]

不管是add()还是addAll()方法, 添加到HashSet里面的元素都不会有重复的,程序会自动去掉重复的。

(3) 遍历元素
第一种方法, forEach遍历

for (String value : set ) {    System.out.println(value);}

第二种方法, 迭代器遍历

Iterator<String> iterator = set.iterator();while (iterator.hasNext()) {    String value = iterator.next();    System.out.println(value);}

公众号

原创粉丝点击