zoukankan      html  css  js  c++  java
  • Java Comparator方法 和 Comparable接口

    默认的排序方法:

      让类继承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(); } }
  • 相关阅读:
    <q>标签,短文本引用
    使用<span>标签为文字设置单独样式
    html速查表
    禁用第三方键盘
    画虚线的方法 (记录)
    渐变色以及隐藏输入框光标
    iOS9 网络适配
    iOS 截屏/将图片存储到相册或沙盒目录下
    从任意字符串中获取所有的数字
    IOS开发
  • 原文地址:https://www.cnblogs.com/vincenshen/p/10162184.html
Copyright © 2011-2022 走看看