【Java to Architect】HashSet TreeSet 集合 红黑树

本文探讨了Java中的Set集合,特别是HashSet和TreeSet。HashSet基于哈希表实现元素唯一性,添加元素时依赖hashCode()和equals()方法。而TreeSet利用红黑树结构,提供排序功能。通过示例展示了如何在HashSet中添加元素以及在TreeSet中实现自定义排序,无论是通过实现Comparable接口还是使用Comparator。
摘要由CSDN通过智能技术生成

概论

  • Set集合继承了AbstractCollection集合,它的核心特点是没有重复元素,无序。
  • TreeSet集合(红黑树),在没有重复元素的基础上,还能够将元素进行排序储存。

Set

我将通过典型的HashSet来了解Set的特性。HashSet实现Set的方式是通过Hash表确保元素的唯一性。而Hash表中,又将分别进行两个动作来判断将要储存的元素是否唯一。

  1. *hashCode()*方法
  2. equals() 方法

在往HashSet内添加值时,会分别进行以上两个步骤。HashSet允许储存:

  • 与现有元素集哈希值不同的元素
  • 与现有元素集哈希值相同,但是 equals() 返回false的元素。

除了以上两种元素,其他元素都会被拒之门外。
因此,在使用HashSet储存对象时,我们需要重写对象的这两个方法,以便满足我们对储存对象数据唯一性的要求。

HashSet例子:

在这个例子中,我写了一个Band类,在这个类中,有三个内部变量:namestylerate, 在判断HashCode上,我选择用namerate判断,在equals上,我选择namestyle判断。

class Band implements {
   
    private String name;
    private String style;
    private int rate;

    Band() {
   

    }

    public Band(String name, String style, int rate) {
   
        this.name = name;
        this.style = style;
        this.rate = rate;
    }

    public String getName() {
   
        return this.name;
    }

    public String getStyle() {
   
        return this.style;
    }

    public int getRate() {
   
        return this.rate;
    }

    public void setRate(int rate) {
   
        this.rate = rate;
    }

    @Override
    public int hashCode() {
   
        System.out.println(this.toString() + "'s hashCode: " + this.name.hashCode() + this.rate * 37);
        return this.name.hashCode() + this.rate * 37;
    }

    @Override
    public boolean equals(Object obj) {
   
        System.out.println(this + "---equals---" + obj);
        if (obj instanceof Band) {
   
            Band bd  = (Band)obj;
            return this.name.equals(bd.name) && this.style.equals(bd.style);
        } else {
   
            return false;
        }
    }

    @Override
    public String toString() {
   
        return "Band@name: " + this.name + " style: " + this.style + " rate: " + this.rate;
    }
}

在主方法中,我们来尝试一下HashSet判断一致性的过程:

public static void main(String[] args) {
   
        HashSet<Band> hs = new HashSet<Band>();
        hs.add(new Band("Smashing Pumpkins", "Rock", 99));
        hs.add(new Band("Smashing Pumpkins", "Rock", 98));
        hs.add(new Band("Smashing Pumpkins", 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值