• Set TreeSet


    package com.dh.learn.collection;
    
    import java.util.Set;
    import java.util.TreeSet;
    
    public class LearnTreeSet {
        public static void main(String[] args) {
            //TreeSet会按照元素顺序排序。是用TreeMap的key实现的。
            // HashSet判断元素是否一致: hashCode + equals
            // TreeSet判断元素是否一致:compareTo  返回结果是0
    
            Set<Person> set = new TreeSet<>();
            set.add(new Person("dh1", 12));
            set.add(new Person("dh2", 12));
            // dh2-12 由于compareTo返回是0 所以TreeSet将其视为一个元素
            set.add(new Person("dh2", 12));
            set.add(new Person("dh2", 13));
            set.add(new Person("dh4", 12));
    
            System.out.println(set);
        }
    
        static class Person implements Comparable {
            String name;
            int age;
    
            public Person(String name, int age) {
                this.name = name;
                this.age = age;
            }
    
            @Override
            public String toString() {
                return name + "===" + age;
            }
    
            @Override
            public int compareTo(Object o) {
                Person p2 = (Person) o;
                int x = name.compareTo(p2.name);
                if (x == 0) {
                    return age - p2.age;
                }
                return x;
            }
        }
    
    }
  • 相关阅读:
    函数配接器
    函数对象和函数指针
    unary_function 和 binary_function
    堆排序
    Shell排序
    volatile理解
    死锁
    进程间通信
    优化循环的方法-循环展开
    如何学习编译原理
  • 原文地址:https://www.cnblogs.com/han6/p/11341704.html
Copyright © 2020-2023  润新知