默认的排序方法:

  让类继承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. FIR滤波器与IIR滤波器

    FIR(Finite Impulse Response)滤波器 有限长单位冲激响应滤波器,又称为非递归型滤波器 特点: FIR滤波器的最主要的特点是没有反馈回路,稳定性强,故不存在不稳定的问题: FI ...

  2. Python使用MySQL数据库的

    然而,2016年开始,我从Python2切换到了Python3,Python2已经基本不再使用,MySQLdb驱动从2014年1月停止了维护.所以,打算重新再来写这篇博客. Python2 ---&g ...

  3. 12个十分实用的JavaScript小技巧

    12个非常实用的JavaScript小技巧 在这篇文章中将给大家分享12个有关于JavaScript的小技巧.这些小技巧可能在你的实际工作中或许能帮助你解决一些问题. 使用!!操作符转换布尔值 有时候 ...

  4. 头一次玩博客,记录下我的java之路吧

    今天写了简单的后台管理系统,发现光靠脑子记住知识真的很难,笔记本不好翻,之前写的代码更难找,所以写写博客,记录一些知识,为了以后上班用得到.

  5. Log4j 使用

    源博客 http://www.cnblogs.com/alipayhutu/archive/2012/06/21/2558249.html#3159794 [1]从零开始 a). 新建Java Pro ...

  6. drawableRightset 和 CompoundDrawables

    android:drawableRight="@drawable/check_down" 在代码中的用法是: Drawable drawable = getResources(). ...

  7. 关于angularjs的select下拉列表存在空白的解决办法

    angularjs 的select的option是通过循环造成的,循环的方式可能有ng-option或者</option  ng-repeat></option>option中 ...

  8. 如何使用 stl 进行排列组合?

    #include <iostream> #include <vector> #include <algorithm> //从 indexs 集合中选择 num 个元 ...

  9. 从B 树、B+ 树、B* 树谈到R 树(转)

      作者:July.weedge.Frankie.编程艺术室出品. 说明:本文从B树开始谈起,然后论述B+树.B*树,最后谈到R 树.其中B树.B+树及B*树部分由weedge完成,R 树部分由Fra ...

  10. python多线程(三)

    同步锁 两个需要注意的点: 线程抢的是GIL锁,GIL锁相当于执行权限,拿到执行权限后才能拿到互斥锁Lock,其他线程也可以抢到GIL,但如果发现Lock仍然没有被释放则阻塞,即便是拿到执行权限GIL ...