默认的排序方法:

  让类继承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. ORACL EXP导出数据说明

    转载自:http://www.jb51.net/article/17358.htm Oracle 数据库导出(exp)导入(imp)说明   exp 将数据库内的各对象以二进制方式下载成dmp文件,方 ...

  2. 页面加载,使用ajax查询某个类别,并且给它们添加(拼接)连接

    直接上代码 $(function(){ var a = ''; $.get("productType1_findAll.action",function(data){ consol ...

  3. php通过post将表单数据保存到数据库实例

    html的form表单 <form id="contact-form" method="POST" action="../php/msg.php ...

  4. Cocos2d-x Lua中网格动作

    GridAction它有两个主要的子类Grid3DAction和TiledGrid3DAction,TiledGrid3DAction系列的子类中会有瓦片效果,如下图所示是Waves3D特效(Grid ...

  5. camke GUI工具 选择 vs2017 时,如何指定工具集 v140 而不是默认的 v141?

    在参数位置加入 v140 即可,不需要加 -T

  6. Js算两经纬度间球面距离

    function GetDistance( lat1, lng1, lat2, lng2){ var radLat1 = lat1 * Math.PI / 180.0 var radLat2 = la ...

  7. Python线程包装器

    import threading import subprocess import time def need_thread(func, *args, **kwargs): def fun(): pr ...

  8. 通过实例来分析I2C基本通信协议

    本文旨在用最通俗易懂的方式.让大家明确I2C通信的过程到底是怎么回事. I2C起源于飞利浦公司的电视设计,但之后朝通用路线发展,各种电子设计都有机会用到I2C 总的来说,I2C能够简单归纳为,两根线, ...

  9. OpenCV3计算机视觉+python(二)

    不同色彩空间的转换 当前,在计算机视觉中有三种常用的色彩空间:灰度.BGR以及HSV 1.灰度色彩空间是通过去除彩色信息来将其转换为灰阶,灰度色彩空间对中间处理特别有效,比如人脸检测 2.BGR,即蓝 ...

  10. 2.5 使用ARDUINO做主控,手机发送短信控制开关LED

    需要准备的硬件 MC20开发板 1个 https://item.taobao.com/item.htm?id=562661881042 GSM/GPRS天线 1根 https://item.taoba ...