• Java-TreeSet的用法-入门


    Java语言中,Set接口有3种通用实现:HashSetTreeSet,LinkedHashSet。TreeSet是一种能够对内部元素进行排序的集合,它使用红黑树来存储内部元素,基于元素的值进行排序,它比HashSet要慢。

    TreeSet要求内部元素实现Comparable接口,因为它是根据元素的compareTo来排序的。下面是一个demo:

    package Colloections;
    
    import java.util.LinkedList;
    import java.util.TreeSet;
    
    public class TreeSetDemo {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            TreeSet<Person> treeSet = new TreeSet<Person>();
            treeSet.add(new Person("albert", 8));
            treeSet.add(new Person("bob", 5));
            treeSet.add(new Person("bob", 13));
            
            for (Person person : treeSet) {
                System.out.printf(person.toString());
            }
        }
    }
    
    class Person implements Comparable<Person>{
    
        public String name;
        public int age;
        
        public Person(String n, int a){
            name = n;
            age = a;
        }
        
        public  String toString() {
            return String.format("Name is %s, Age is %d%n", name, age);
        }
        
        @Override
        public int compareTo(Person o) {
            // TODO Auto-generated method stub
            int nameComp = this.name.compareTo(o.name);
            return (nameComp != 0 ? nameComp : (this.age - o.age));
        }
        
    }

    程序输出为:

    Name is albert, Age is 8
    Name is bob, Age is 5
    Name is bob, Age is 13

  • 相关阅读:
    hdu1828线段树(两次扫描+离散化)
    hdu1542线段树(扫描线+离散化)
    二分思想
    hdu2871线段树区间更新
    git初体验
    python笔记-模块
    python笔记-动态类型
    AWS上创建EKS(K8S)集群
    Akamai CDN刷新(通过Akamai cli 自动刷新)
    创建Akamai cdn api授权
  • 原文地址:https://www.cnblogs.com/pzy4447/p/5024197.html
Copyright © 2020-2023  润新知