java的两个比较器

java实现比较功能的类,有两种解决方案。分别继承comparable和compartor接口。

1 继承comparable

  实现比较功能的类直接继承该接口,并重写compareTo方法。相关代码如下:

public class BookCook implements Comparable<BookCook>{
    /**
     * 主题
     */
    private String title;

    /**
     * 价格
     */
    private Double price;

    public BookCook(String title, Double price) {
        this.title = title;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public int compareTo(BookCook o) {
        if (this.price > o.price) {
            return 1;
        } else if (this.price < o.price) {
            return -1;
        }
        return 0;
    }

    @Override
    public String toString() {
        return "书名:"+this.title+",价格:"+this.price;
    }
}
// 测试接口
public static void main(String[] args) {
        BookCook[] bookCooks = new BookCook[]{
                new BookCook("书籍1", (double) 20),
                new BookCook("书籍2", (double) 30),
                new BookCook("书籍3", (double) 10),
                new BookCook("书籍4", (double) 70),
                new BookCook("书籍5", (double) 50)
        };

        Arrays.sort(bookCooks);
        for (BookCook bookCook : bookCooks) {
            System.out.println(bookCook);
        }
    }

2 继承compartor

  不改变比较类的前提下,只需要写一个xxxCompartor(命名随意)来实现Compartor接口即可,同时重写compare方法。相关代码如下所示:

// 比较类
public class Student {
    /**
     * 学生姓名
     */
    private String name;

    /**
     * 学生得分
     */
    private Double score;

    public Student(String name, Double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getScore() {
        return score;
    }

    public void setScore(Double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "姓名:"+this.name+",分数:"+this.score;
    }
}

public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getScore()>o2.getScore()) {
            return 1;
        } else if (o1.getScore()<o2.getScore()) {
            return -1;
        }
        return 0;
    }
}
// 测试接口
public static void main(String[] args) {
    Student[] sts = new Student[]{
            new Student("小戴", (double) 60),
            new Student("小王", (double) 90),
            new Student("老王", (double) 80),
            new Student("小萱", (double) 95)
    };
    Arrays.sort(sts, new StudentComparator());
    System.out.println(Arrays.toString(sts));
}
发布了39 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/a1920135141/article/details/101112128
今日推荐