集合_向TreeSet中存储自定义类型.

TreeSet使用了二叉树的数据结构,负数放到左边,正数放到右边。

    ■当compareTo方法返回0的时候,系统会认为两者- 致,所以不会向集合中添加元素

    ■当compareTo方法返回正数的时候,系统将元素存储到右边,所以集合存取顺序一致


.当compareTo方法返回负数的时候, 刺痛将元素存储到左边,所以集合会倒序存储



案例

public int compareTo (Person 0) {

//先根据年龄进行排序

int num =this.age - o.getAge() ;

/ /如果年龄相等,再根据姓名进行排序

if(num == 0) {

num = this.name. compareTo (o.getName()) ;

return num;

}

}

public class TreeSetTest02 {

public static void main (String[] args) {

TreeSet ts = new TreeSet<>() ;

/ /String中无法对中文进行排序,因为里面的compareTo方法是计算的两个char类型的之差

ts. add (new Person("james",20)) ;

ts. add (new Person("lucy",22) ) ;

ts. add (new Person("lyn",20)) ;

ts. add (new Person ("paul",21) ) ;

ts. add (new Person ("jordan",24) ) ;

System. out.println(ts) ;

}

Comparator比较器

自定义比较器

package com . monkey1024. set;

import java . util . Comparator;

import com . monkey1024. bean. Person;

public class CompareByLength implements Comparator {

        @Override

        pub1ic int compare (Person p1,Person p2) {

            int num = p1. getName () . length() - p2. getName () . length() ;

            if(num==0){

                    num = p1. getName (). compareTo (p2. getName() );

             }

            if(num == 0) {

            num= p1.getAge() 一p2.getAge () ;

            return num;

}

}

}

package com .monkey1024. set;

import j ava. util. Treeset;

import com. monkey1024.bean. Person;

public class TreeSetTest03 {

    public static void main (String[] args) {

            / /调用有参构造方法,将自定义比较器的对象传入

            Treeset ts = new TreeSet<> (new CompareByLength()) ;

            ts. add (new Person ("jordan", 40)) ;

            ts . add (new Person ("lucy", 10) ) ;

            ts . add (new Person("an", 20) ) ;

            ts . add (new Person ("james",30)) ;

            ts. add (new Person("matt", 45)) ;

                System. out. println (ts) ;

}

}

一个小练习题

问题:将一个字符串中的字符按照字典顺序进行排序,要保留重复的字符。例如输入: java,打印aajv

分析:使用TreeSet进行排序,重写compareTo方法,如果是0的话返回1

public class Exercise03 {

        public static void main (String[] args) {

                Scanner S = new Scanner ( System. in) ;

                System. out. println ("请输入一个字符串:") ;

                String line = s.nextLine() ;

                char[] array = line. toCharArray() ;

                TreeSet ts = new TreeSet<> (new Comparator ()) {

                        @Override

                        public int compare (Character o1,Character o2) {

                                int num = o1 . compareTo(o2) ;

                                / /如果结果是0的话返回1,防止重复数据不会存储到set中

                                return num == 0 ? 1 : num;

                           }

                    }

                / /将数组中的元素放入到TreeSet中

                for (Character C : array) {

                ts.add(c) ;

        }

    for(Character c: ts){

            System.out.println(c);

    }

}

你可能感兴趣的:(集合_向TreeSet中存储自定义类型.)