默认的排序方法:

  让类继承Comparable接口,重写compareTo方法。

示例代码:

package com.imooc.collection;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set; /**
* 学生类
* Set中的元素是唯一的,不会重复,但是没有顺序。
*/ public class Student implements Comparable<Student>{

private String id; private String name; // set集合只能使用 foreach 或 iterator进行遍历,不能使用get()来获取元素
public Set <Course> course; public Student(){ } public Student(String id, String name){
this.id = id;
this.name = name;
this.course = new HashSet<>();
} public void setId(String id) {
this.id = id;
} public void setName(String name) {
this.name = name;
} public void setCourse(Set<Course> course) {
this.course = course;
} public String getId() {
return id;
} public String getName() {
return name;
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name);
} @Override
public int hashCode() {
return Objects.hash(name);
} public Set getCourse() {
return this.course;
} @Override
public int compareTo(Student o) {
// 对ID进行排序
return this.id.compareTo(o.id);
}

}

  

临时的排序方法:

  Collection类自身有一个sort方法,需要传入一个 Comparator 类,并重写它的compare方法。

示例代码:

package com.imooc.collection;
import java.util.*; public class SetTest { private final List <Course> coursesToSelect = new ArrayList<>(); private final Scanner scanner = new Scanner(System.in); private Student student; public SetTest(){ } // 用于往courseToSelect中添加备选课程
public void testAdd(){
// 创建一个课程对象,并通过调用add方法,添加到备选课程List中
Course cr1 = new Course("1", "数据结构");
coursesToSelect.add(cr1); Course cr2 = new Course("2", "C语言");
coursesToSelect.add(0, cr2); // Course数组
Course[] course = {new Course("3", "离散数学"), new Course("4", "汇编语言")};
coursesToSelect.addAll(Arrays.asList(course)); Course[] course2 = {new Course("5", "高等数学"), new Course("6", "大学英语")};
coursesToSelect.addAll(2, Arrays.asList(course2)); } /**
* 通过 foreach 方法来遍历List
*/
public void testForeach(){
// System.out.println("(foreach)有如下课程待选:");
for (Object obj: coursesToSelect) {
Course cr = (Course) obj;
System.out.println("课程:" + cr.getId() + ":" + cr.getName()); }
} /**
* 遍历Student集合中的所有元素
* @param student
*/
public void testForeachSet(Student student){
// 打印学生所选课程
for(Course cr: student.course) {
System.out.println("选择了课程:" + cr.getId() + ":" + cr.getName());
}
} /**
* 测试List的 contains 方法
* @param
*/
public void testListContainers(){
// 获取备选课程序列的第0个元素
Course course = coursesToSelect.get(0); // 打印输出coursesToSelected是否包含course对象
System.out.println("取得课程:" + course.getName());
System.out.println("备选课程中是否包含课程:" + course.getName() + "," + coursesToSelect.contains(course)); // 提示输入课程名称
System.out.println("请输入课程名称:");
String name = scanner.next();
Course course2 = new Course();
course2.setName(name);
// 创建一个新的课程对象, ID和名称 与course对象完全一样
// Course course2 = new Course(course.getId(), course.getName());
System.out.println("新创建课程对象:" + course2.getName());
System.out.println("备选课程中是否包含课程:" + course2.getName() + ","+ coursesToSelect.contains(course2)); // 通过indexOf()方法来获取某元素的索引位置
if(coursesToSelect.contains(course2)){
System.out.println("课程:" + course2.getName() + "的索引位置为:" + coursesToSelect.indexOf(course2));
} coursesToSelect.sort(new Comparator<Course>() {
       // 重写compare方法 
@Override
public int compare(Course o1, Course o2) {
if(Integer.parseInt(o1.getId()) > Integer.parseInt(o2.getId())){
return 0;
}
return -1;
}
});
for(Course cr: coursesToSelect){
System.out.println("课程ID:" + cr.getId() + "课程名称:" + cr.getName());
}
}public static void main(String args[]){
SetTest st = new SetTest();
st.testAdd();
st.testForeach(); st.testListContainers();
}
}

Java Comparator方法 和 Comparable接口的更多相关文章

  1. Effective Java 【考虑实现Comparable接口】

    Effective Java --Comparable接口 compareTo方法是Comparable接口的唯一方法.类实现了Comparable接口,表明它的实例具有内在的排序关系. 自己实现co ...

  2. Java自定义排序:继承Comparable接口,重写compareTo方法(排序规则)

    代码: 1 import java.util.*; 2 3 /** 4 * 学习自定义排序:继承Comparable接口,重写compareTo方法(排序规则). 5 * TreeMap容器的Key是 ...

  3. Java连载89-SorteSet、Comparable接口

    一. SortedSet集合直接举例 package com.bjpowernode.java_learning; import java.util.*; /** * java.util.Set * ...

  4. Comparable 接口与Comparator的使用的对比

    package com.yhqtv.java; import org.junit.Test; import java.util.Arrays; import java.util.Comparator; ...

  5. Item 12 考虑实现Comparable接口

    1.Comparable接口,用来做什么. 2.判定类实现的Comparable接口是否正确的方法. 3.不要扩展一个已经实现了Comparable接口的类来增加用于比较的值组件.     1.Com ...

  6. Comparable接口的实现和使用

    1.什么是Comparable接口 此接口强行对实现它的每个类的对象进行整体排序.此排序被称为该类的自然排序 ,类的 compareTo 方法被称为它的自然比较方法 .实现此接口的对象列表(和数组)可 ...

  7. java实现Comparable接口和Comparator接口,并重写compareTo方法和compare方法

    原文地址https://segmentfault.com/a/1190000005738975 实体类:java.lang.Comparable(接口) + comareTo(重写方法),业务排序类 ...

  8. Java集合中Comparator和Comparable接口的使用

    在Java集合中,如果要比较引用类型泛型的List,我们使用Comparator和Comparable两个接口. Comparable接口 -- 默认比较规则,可比较的 实现该接口表示:这个类的实例可 ...

  9. java 中的2个接口 Comparable和Comparator

    像Integer.String这些类型的数据都是已经实现Comparable接口的,所以对这些类型可以直接通过Arrays.sort(...)和Collections.sort(...)方法进行排序. ...

随机推荐

  1. 如何使用NSOperations和NSOperationQueues

    原文地址: http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues 本文由 大侠自来也(泰然教 ...

  2. class 中构造函数与析构函数

    import pymysql class My_sql(): def __init__(self, host, user, passwd, db, port=3306, charset='utf8') ...

  3. 《从零开始学Swift》学习笔记(Day 36)——静态方法

    原创文章,欢迎转载.转载请注明:关东升的博客 静态方法与静态属性类似,Swift中定义了静态方法,也称为类型方法.静态方法的定义与静态属性类似,枚举和结构体的静态方法使用的关键字是static:类静态 ...

  4. 3N Numbers

    D - 3N Numbers Time limit : 2sec / Memory limit : 256MB Score : 500 points Problem Statement Let N b ...

  5. Python3.6全栈开发实例[022]

    22.完成彩票36选7的功能. 从36个数中随机的产生7个数. 最终获取到7个不重复的数据作为最终的开奖结果.随机数: from random import randintrandint(0, 20) ...

  6. 【生产问题】--8KW的数据表导致业务卡顿

    问题描述:业务突然变得巨卡 分析思路: (1)分析用户请求进程:查看是否有长期运行霸占锁的情况,或者进程数量巨多.很明显我这里就是巨多,正常情况一般0~40来个的样子,在业务使用高峰期居然达到了140 ...

  7. boost之数据结构和容器

    1.静态数组array,boost对静态数组进行了封装,使用和普通数组一样的初始化式进行初始化. #include <iostream> #include <boost/array. ...

  8. activiti部署到linux后流程图不显示汉字的问题

    linux和windows的字体文件一般是不一样的,默认情况下,linux的java7中一般不支持中文,activiti的动态流程图中的汉字需要java调用汉字的字库,这里需要配置一下java的汉字字 ...

  9. 神奇的Timer

    最近的一个项目有一些地方需要用到定时功能,在设计过程中,突然发现.net的Timer类居然还有很多我以前没有用过的功能,这里就跟大家分享一下 注:这里的Timer类特指System.Threading ...

  10. 高阶函数,map,filter,sorted

    Map:对列表中的每个元素进行操作 >>> def f(x): ...    return x * x ... >>> map(f, [1, 2, 3, 4, 5, ...