Set集合

概述

  1. 继承Collection集合

  2. 无序,无索引,元素不可重复,意味着我们不能用正常的for来遍历里面的元素

  3. 通过哈希表来实现存储,因此自定义对象的时候想要实现去重功能必须重写hashCode和equals方法

  4. 遍历set里面的集合用迭代器或增强for(增强for本质上是迭代器)

HashSet<String> set = new HashSet<String>();
set.add(new String("AA"));
set.add("BB");
set.add("CC");
set.add("AA");
for (String name : set) {
  System.out.println(name);
}

 

HashSet存储自定义类型

HashSet<Student> stuSet = new HashSet<Student>();
Student stu = new Student("AA", 10);
stuSet.add(stu);
​
stuSet.add(new Student("BB", 15));

 

LinkedHashSet集合

由于Hashet是无序存储,在平时使用中我们经常要排序等操作,就要使用LinkedHashSet集合,它集成了HashSet能保证元素唯一性,且又能实现有序存储

Set<String> set = new LinkedHashSet<String>();
set.add("AA");
set.add("DD");
set.add("CC");
set.add("BB");
Iterator it = set.iterator();
while (it.hasNext()) {
  String str=it.next();
  System.out.println(str;
}

 

posted @ 2018-08-16 17:25  205李华秋  阅读(177)  评论(0编辑  收藏  举报