Set接口
Set接口的方法与Collection接口的方法完全一致,由于其特点为无序、不可重复所以与List接口相比,少了索引的有关方法,当要查找元素时只能通过遍历查找,常用的实现类有HashSet、TreeSet等。
HashSet
HashSet底层使用了HashMap,可以把HashSet看成一个化简之后的HashMap,其化简之处在于,将HashMap的键值对的值对象定义为常量,将想要存入HashSet中的元素作为其底层HashMap的键对象存入底层的HashMap中去。这也是为何HashSet不可重复的原因,HashMap中的key对象时不可重复的。
可放入null。
//HashSet底层源码
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
TreeSet
TreeSet与上文HashSet类似,底层使用了TreeMap,将存入的元素作为键对象存入底层的TreeMap。
TreeSet内部自动按照元素递增的方式将元素排序。如果要对自定义的类进行排序,该类必须实现Comparable接口。
public class TreeSetTest {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
set.add(1);
set.add(5);
set.add(3);
for (Integer integer:set){
System.out.println(integer);//1,3,5
}
Set<Garden> set02 = new TreeSet<>();
set02.add(new Garden("Makka Pakka",1,10));
set02.add(new Garden("Igglepiggle",2,9));
set02.add(new Garden("Upsy Daisy",3,8));
for (Garden tar:set02){
System.out.println(tar.getName());//Upsy Daisy
//Igglepiggle
//Makka Pakka
}
}
//Comparable接口复习
static class Garden implements Comparable<Garden>{
private String name;
private int id;
private int age;
public String getName() {
return name;
}
public Garden(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
//负数小于 正数大于 等于零,此处根据年龄排序
public int compareTo(Garden o) {
if (this.age>o.age){
return 1;
}else if(this.age<o.age){
return -1;
}else{
return 0;
}
}
}
}