Set 接口

实现类一HashSet

最显著的特点是,HashSet类中的元素不能重复。

底层的逻辑和方法的调用

/*

Set 接口 不能存储重复元素

HashSet

元素是无序的(既不是添加顺序,也不是按元素的自然顺序)

向Hashset中添加元素时,是如何判断元素是否重复的

添加元素时 调用equals()判断, 效率低(一个一个字符判断)

底层用到hashCode() 和 equals() 方法

xsadasdsadsasa 用内容计算一个hash值(整数),用hash值比较速度快

但是hash是不安全,有可能内容不同,计算的hash值相同,

当hash相同时,调用equals()判断内容是否相等

这样既效率提高了 也保证安全

*/

HashSet<Student> set = new HashSet<>();

Student student1 = new Student(101,"张三");

Student student2 = new Student(102,"李四");

Student student3 = new Student(103,"王五");

Student student4 = new Student(101,"张三");

/*

添加时,判断会调用类中hashCode()计算hash值, 类中,没有hashCode(),会调用父类中的hashCode()

Object类中的 public native int hashCode(); native本地方法(操作系统提供的)

所以只要是new出来的,调用Object类中hash值,是内存地址,肯定不相同

如果我们想要对象中的内容相等就判定为重复元素,就必须在我们的类中重写hashCOde() equals() 用对象中的内容来计算hash值

*/

set.add(student1);

set.add(student2);

set.add(student3);

set.add(student4);

实现类二TreeSet

可以给Set集合中的元素进行指定方式的排序。存储的对象必须实现Comparable接口

底层的逻辑和方法的调用

/*

Set 不能存储重复元素

TreeSet

底层是树形结构 有一个根节点, 每一个节点有两个子节点, 大的元素向右放,小的元素向左放

添加进来的元素可以排序 (有序的 不是添加的顺序,是元素的自然顺序)

*/

public static void main(String[] args) {

TreeSet<Student> set = new TreeSet<>();

Student student1 = new Student(101,"张三");

Student student2 = new Student(102,"李四");

Student student3 = new Student(103,"王五");

Student student4 = new Student(101,"张三");

set.add(student2);

set.add(student4);

set.add(student3);

set.add(student1);

}(Student类时自己创建的类,并且已经对方法进行了重写)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值