编程语言
首页 > 编程语言> > Java-TreeMap

Java-TreeMap

作者:互联网

Java-TreeMap

package com.unicom.www;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetTest {
    public static void main(String[] args) {
//        利用重写Comparator接口,实现自写类的可排序。
        TreeSet<XiaoWuGui> integers = new TreeSet<>(new cmp());
//        利用重写Comparable接口,实现自写类的可排序
//        TreeSet<XiaoWuGui> integers = new TreeSet<>();
        integers.add(new XiaoWuGui(400, "qiaozhi"));
        integers.add(new XiaoWuGui(300,"peiqi"));
        integers.add(new XiaoWuGui(200,"nini"));
        integers.add(new XiaoWuGui(500,"baba"));
        integers.add(new XiaoWuGui(480,"mama"));
        integers.add(new XiaoWuGui(800,"papa"));
        integers.add(new XiaoWuGui(800,"nainai"));
        integers.add(new XiaoWuGui(807,"nainai"));

        for (XiaoWuGui i:integers
             ) {
            System.out.println(i);
        }
        System.out.println("------------------------------------");
//        将Set转化为List
        ArrayList<XiaoWuGui> xiaoWuGuis = new ArrayList<>(integers);
//        利用Collections工具类可保证线程安全
        Collections.synchronizedList(xiaoWuGuis);
//        Collections.sort()方法需要自写类实现Comparable接口
        Collections.sort(xiaoWuGuis);
        for (XiaoWuGui x:xiaoWuGuis
             ) {
            System.out.println(x);

        }
    }

}

 class cmp implements Comparator<XiaoWuGui>{
    @Override
    public int compare(XiaoWuGui o1, XiaoWuGui o2) {
//        return (o1.age+o1.name).compareTo(o2.age+o2.name);
        return (o1.name+o1.age).compareTo(o2.name+o2.age);
    }
}
 class XiaoWuGui implements Comparable<XiaoWuGui>{
    int age;
    String name;

     @Override
     public int compareTo(XiaoWuGui o) {
         return this.age-o.age;
     }

     @Override
     public String toString() {
         return "XiaoWuGui{" +
                 "age=" + age +
                 ", name='" + name + '\'' +
                 '}';
     }

     public XiaoWuGui(int age, String name) {
        this.age = age;
        this.name = name;
    }
}

标签:integers,Java,name,age,TreeMap,add,new,XiaoWuGui
来源: https://www.cnblogs.com/yezi44271/p/15636290.html