Java基础 TreeSet()来实现数组的【定制排序】 : Comparable接口(自然排序) 或者 Comparator接口 (定制排序)

笔记:

 //排序真麻烦!没有C++里的好用又方便!ORZ!ORZ!数组排序还还自己写个TreeSet()和( Comparable接口(自然排序) 或者 Comparator接口 (定制排序))
import
java.util.*; import java.lang.*; /**对象排序 * a.实现Comparable接口 + TreeSet()自定义排序 Student[id,name]数组 * 创建一个Student类,实现Comparable接口 ,实现按id自动降序排序 * (可以直接引用自然排序compareTo)1.TreeSet<Student> ts2=new TreeSet<Student>(Student::compareTo); * * b.比较器Comparator接口 + TreeSet()自定义排序数组 * b.(定义了匿名的)比较器Comparator(接口) + TreeSet()自定义排序数组 * Comparator<Student> com = new Comparator<>() { ...阔以自动生成! } */

测试代码:public class TestSet {

public static void main(String[] args) {
        // a.实现Comparable接口 + TreeSet()自定义排序数组
        Student[] stud=new Student[]{        //需要排序的数组
                new Student(1001,"王大"),
                new Student(1002,"张三"),
                new Student(1003,"李四"),
                new Student(1004,"王五") };
        TreeSet<Student> ts=new TreeSet<Student>();
        for(int i=0;i<stud.length;i++)
            ts.add(stud[i]);
        test_TreeSet(ts);
// b.(定义了匿名的)比较器Comparator(接口) + TreeSet()自定义排序数组 Comparator<Student> com = new Comparator<>() { @Override public int compare(Student o1, Student o2) { //按id从小到大排序//----o2-----o1(在后面)--- 返回1不变,-1颠倒 if(o1.id>o2.id)return 1; else if(o1.id<o2.id) return -1; else return 0; } }; TreeSet<Student> ts3=new TreeSet<Student>(com); for(int i=0;i<stud.length;i++) ts3.add(stud[i]); test_TreeSet(ts3); } static void test(Collection s){ for(Object o:s){ System.out.print(o+"\t"); } System.out.println("---------->>"+s.getClass()+"---------"); } static void test_TreeSet(TreeSet<Student> s){ for(Student o:s){ System.out.print(o.id+" "+o.name+"\t"); } System.out.println("---------->>"+s.getClass()+"---------"); } } class Student implements Comparable<Student>{ int id; String name; public int compareTo(Student s) { //从大到小,降序排序 //----s-----this(在后面)--- 返回1不变,-1颠倒 if(this.id<s.id)return 1; else if(this.id>s.id)return -1; else return 0; } public Student(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } }

测试输出:

猜你喜欢

转载自www.cnblogs.com/zhazhaacmer/p/9787760.html
今日推荐