(JavaSE 学习记录) Set接口、HashSet、TreeSet

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;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值