TreeSet与HashSet的区别

本文深入探讨了HashSet和TreeSet两种集合类型的特点和使用场景。HashSet基于Hash算法实现,无序不重复,性能优越,适合大多数集合操作。TreeSet则提供排序功能,要求元素实现Comparable接口,适用于需要排序的场景。文章通过示例代码展示了如何使用这两种集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HashSet实现Set接口(内部是HashMap),无序不重复,它不保证集合的迭代顺序。如果操作的元素是对象须重写equals和hashcode两方法来保证不重复去存,并且最多包含一个null元素。
TreeSet实现Set接口(内部是TreeMap)。有序不重复,如果TreeSet中元素是对象则必须要实现Comparable接口,否则会抛出Exception in thread "main" java.lang.ClassCastException: com.code.Student cannot be cast to java.lang.Comparable异常。
HashSet与TreeSet都是基于Set接口的实现类,其中TreeSet是Set的子接口SortedSet的实现类。
HashSet是基于Hash算法实现的,其性能通常优于TreeSet,我们通常都应该使用HashSet,在我们需要排序的功能时,我门才使用TreeSet。 

HashSet示例

public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("1");
        set.add("2");
        set.add("1");
        System.out.println(set);
        Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(2);
        set1.add(3);
        System.out.println(set1);
    }

 HashSet集合只能存取包装类,以上代码输出如下;

[1, 2]
[1, 2, 3]

public static void main(String[] args) {
        Set<Student> set = new HashSet<>();
        set.add(null);
        set.add(null);
        set.add(new Student(20,"张山"));
        set.add(new Student(20,"张山"));
        set.add(new Student(40,"张山"));
        System.out.println(set);
    }

HashSet操作Student类,此时没有重写equals和hashcode两方法,输出如下;
[null, Student [age=40, name=张山], Student [age=20, name=张山], Student [age=20, name=张山]]

重写之后输出如下;
[null, Student [age=40, name=张山], Student [age=20, name=张山]]
 

TreeSet示例

public static void main(String[] args) {
        Set<Student> set = new TreeSet<>();
        set.add(null); //不允许null
        set.add(new Student(3,"ss3"));
        set.add(new Student(2,"ss2"));
        set.add(new Student(1,"ss1"));
        set.add(new Student(4,"ss4"));
        System.out.println(set);
    }

Exception in thread "main" java.lang.NullPointerException

public static void main(String[] args) {
        Set<Student> set = new TreeSet<>();
        set.add(new Student(3,"ss3"));
        set.add(new Student(2,"ss2"));
        set.add(new Student(2,"ss2"));
        set.add(new Student(1,"ss1"));
        set.add(new Student(4,"ss4"));
        System.out.println(set);
    }

 [Student [age=1, name=ss1], Student [age=2, name=ss2], Student [age=3, name=ss3], Student [age=4, name=ss4]]

Student类必须实现Comparable<?>接口,重写compareTo(?)方法,否则抛出异常java.lang.ClassCastException: com.code.Student cannot be cast to java.lang.Comparable。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值