zoukankan      html  css  js  c++  java
  • TreeSet的使用和底层实现

     TreeSet底层实际是用TreeMap实现的,内部维持了一个简化版的TreeMap,通过key来存储Set的元素。 TreeSet内部需要对存储的元素进行排序,因此,我们对应的类需要实现Comparable接口。这样,才能根据compareTo()方法比较对象之间的大小,才能进行内部排序。

    【示例】TreeSet和Comparable接口的使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    public class Test {
        public static void main(String[] args) {
            User u1 = new User(1001"高淇"18);
            User u2 = new User(2001"高希希"5);
            Set<User> set = new TreeSet<User>();
            set.add(u1);
            set.add(u2);
        }
    }
     
    class User implements Comparable<User> {
        int id;
        String uname;
        int age;
     
        public User(int id, String uname, int age) {
            this.id = id;
            this.uname = uname;
            this.age = age;
        }
        /**
         * 返回0 表示 this == obj 返回正数表示 this > obj 返回负数表示 this < obj
         */
        @Override
        public int compareTo(User o) {
            if (this.id > o.id) {
                return 1;
            else if (this.id < o.id) {
                return -1;
            else {
                return 0;
            }
        }
    }

    使用TreeSet要点:

          (1) 由于是二叉树,需要对元素做内部排序。 如果要放入TreeSet中的类没有实现Comparable接口,则会抛出异常:java.lang.ClassCastException。

          (2) TreeSet中不能放入null元素。

  • 相关阅读:
    C# Ini配置文件
    C#日志写入
    GZFramework.DB.Core初始化
    httpHelper
    GZFramework代码生成器插件使用教程
    MVC部署IIS设置
    SignalR记录
    洛谷 P2360 地下城主
    洛谷 P1379 八数码难题(map && 双向bfs)
    洛谷 P1155 双栈排序
  • 原文地址:https://www.cnblogs.com/huaxiansheng/p/15317784.html
Copyright © 2011-2022 走看看