![61e9396ef9493146447d062c29d2eacf.png](https://i-blog.csdnimg.cn/blog_migrate/2a686e5e398d2891f92ae85f66ed8101.jpeg)
了解过HashMap和TreeMap后,学习HashSet和TreeSet就显得很简单了——二者底层分别基于前者来实现。
对于HashSet:
![9ac7f527962a2ecddfa57810d0635355.png](https://i-blog.csdnimg.cn/blog_migrate/c75fcb2e5dd5b50c37bc3cfb88bd875c.png)
![25adfdcc0c9e8eec18d7942fe9a958fe.png](https://i-blog.csdnimg.cn/blog_migrate/98a53fe773a9b4cb6adbbaf517aa2f13.png)
![b5e6d614b2a41efa917da9039eaca681.png](https://i-blog.csdnimg.cn/blog_migrate/9a1a9147cc7b955a14c5cf9b5b4a3cb8.png)
至于其余的方法,也基本上是调用了HashMap的方法。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public void clear() {
map.clear();
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
//。。。。。。
值得注意的就是HashSet的无序不可重复性,测试如下:
package myHashMap;
import java.util.HashSet;
import java.util.Set;
public class TestHashSet {
public static void main(String[] args) {
Set<String> hashSet=new HashSet<>();
hashSet.add("a");
hashSet.add("b");
hashSet.add("a");
System.out.println(hashSet);
System.out.println(hashSet.size());
}
}
![6e6e1cdd9de22579bd060237fed3575a.png](https://i-blog.csdnimg.cn/blog_migrate/a72dbfae9149b42d60eaff5b45e2534d.png)
对于TreeSet:
对比HaseSet——>TreeSet底层是有TreeMap实现,具有有序不可重复性的特点。
注:所谓无序和有序我的理解是——输出是否可以与插入元素顺序无关,无关则是有序,有关则是无序,就比如HashSet输出时的顺序总是和插入顺序一致,而TreeSet就可以按照key值排序。
测试如下:
package myHashMap;
import java.util.Set;
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String[] args) {
Set<Integer> treeset = new TreeSet<>();
treeset.add(300);
treeset.add(100);
treeset.add(400);
System.out.println(treeset);
Set<Emp1> treeset1=new TreeSet<>();
treeset1.add(new Emp1(10, "张三", 2000));
treeset1.add(new Emp1(2, "王五", 1000));
treeset1.add(new Emp1(1, "李二", 2000));
System.out.println(treeset1);
}
}
class Emp1 implements Comparable<Emp1> {
public Emp1(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
int id;
String name;
double salary;
@Override
public String toString() {
return "id=" + this.id + " name=" + this.name + " salary=" + this.salary;
}
@Override
public int compareTo(Emp1 o) {
if (this.salary > o.salary) {
return 1;
} else if (this.salary < o.salary) {
return -1;
} else {
if (this.id > o.id) {
return 1;
} else if (this.id < o.id) {
return -1;
} else {
return 0;
}
}
}
}
![818e0deb9af229f07fe22dcd7fbc879d.png](https://i-blog.csdnimg.cn/blog_migrate/bf24fed4eda1a2667e6759d1d5935c48.png)