代码: public class Student implements Comparable<Student> { private int id; private String name; private int age; public Student(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } @Override public int compareTo(Student o
1.Comparable接口 说明:可比较(可排序的) 例子:按照MyClass的y属性进行生序排序 class MyClass implements Comparable<MyClass>{ private int x; private int y; public MyClass(int x,int y){ this.x=x; this.y=y; } @Override public int compareTo(MyClass o) { //按照y进行升序排序 return y<o.y
一.前言 在Java集合框架里面,各种集合的操作很大程度上都离不开Comparable和Comparator,虽然它们与集合没有显示的关系,但是它们只有在集合里面的时候才能发挥最大的威力.下面是开始我们的分析. 二.示例 在正式讲解Comparable与Comparator之前,我们通过一个例子来直观的感受一下它们的使用. 首先,定义好我们的Person类 class Person { String name; int age; public Person(String name, int ag
import java.util.Arrays; public class SortApp { public static void main(String[] args) { Student[] stus = new Student[3]; stus[0] = new Student(11, 99); stus[1] = new Student(13, 92); stus[2] = new Student(13, 89); Arrays.sort(stus); for (Student stu