wordpress方框里面打勾,两个域名同一个网站做优化,花的网页设计模板素材,搜索案例的网站day03 【List、Set、数据结构、Collections】
5.3 简述Comparable和Comparator两个接口的区别。
Comparable#xff1a;强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序#xff0c;类的compareTo方法被称为它的自然比较方法。只能在类中实现compareTo…day03 【List、Set、数据结构、Collections】
5.3 简述Comparable和Comparator两个接口的区别。
Comparable强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序类的compareTo方法被称为它的自然比较方法。只能在类中实现compareTo()一次不能经常修改类的代码实现自己想要的排序。实现此接口的对象列表和数组可以通过Collections.sort和Arrays.sort进行自动排序对象可以用作有序映射中的键或有序集合中的元素无需指定比较器。
Comparator强行对某个对象进行整体排序。可以将Comparator 传递给sort方法如Collections.sort或 Arrays.sort从而允许在排序顺序上实现精确控制。还可以使用Comparator来控制某些数据结构如有序set或有序映射的顺序或者为那些没有自然顺序的对象collection提供排序。
5.4 练习
创建一个学生类存储到ArrayList集合中完成指定排序操作。
Student 初始类
public class Student{private String name;private int age;public Student() {}public Student(String name, int age) {this.name name;this.age age;}public String getName() {return name;}public void setName(String name) {this.name name;}public int getAge() {return age;}public void setAge(int age) {this.age age;}Overridepublic String toString() {return Student{ name name \ , age age };}
}测试类
public class Demo {public static void main(String[] args) {// 创建四个学生对象 存储到集合中ArrayListStudent list new ArrayListStudent();list.add(new Student(rose,18));list.add(new Student(jack,16));list.add(new Student(abc,16));list.add(new Student(ace,17));list.add(new Student(mark,16));/*让学生 按照年龄排序 升序*/
// Collections.sort(list);//要求 该list中元素类型 必须实现比较器Comparable接口for (Student student : list) {System.out.println(student);}}
}发现当我们调用Collections.sort()方法的时候 程序报错了。
原因如果想要集合中的元素完成排序那么必须要实现比较器Comparable接口。
于是我们就完成了Student类的一个实现如下
public class Student implements ComparableStudent{....Overridepublic int compareTo(Student o) {return this.age-o.age;//升序}
}再次测试代码就OK 了效果如下
Student{namejack, age16}
Student{nameabc, age16}
Student{namemark, age16}
Student{nameace, age17}
Student{namerose, age18}5.5 扩展
如果在使用的时候想要独立的定义规则去使用 可以采用Collections.sort(List list,Comparetor c)方式自己定义规则
Collections.sort(list, new ComparatorStudent() {Overridepublic int compare(Student o1, Student o2) {return o2.getAge()-o1.getAge();//以学生的年龄降序}
});效果
Student{namerose, age18}
Student{nameace, age17}
Student{namejack, age16}
Student{nameabc, age16}
Student{namemark, age16}如果想要规则更多一些可以参考下面代码
Collections.sort(list, new ComparatorStudent() {Overridepublic int compare(Student o1, Student o2) {// 年龄降序int result o2.getAge()-o1.getAge();//年龄降序if(result0){//第一个规则判断完了 下一个规则 姓名的首字母 升序result o1.getName().charAt(0)-o2.getName().charAt(0);}return result;}});效果如下
Student{namerose, age18}
Student{nameace, age17}
Student{nameabc, age16}
Student{namejack, age16}
Student{namemark, age16}