Home > Java > javaTutorial > body text

Detailed explanation of sample code of Java Comparable interface

黄舟
Release: 2017-03-20 11:09:46
Original
1479 people have browsed it

This article is part of the free Java 8 course on Clean Code principles.

In this article, we are going to talk about Java ComparableInterface.

There is also a good video you can click here.

What is the Comparable interface used for?

How should we compare and sort things? This question may sound a bit confusing, but I hope you will think about it seriously. For example, we have a group of apples:

Example 1

How do we sort them? Do we want to sort by weight? If so, are they sorted from lightest to heaviest or heaviest to lightest? When we sort them, we need to repeatedly compare the weight of the two apples until all the apples are sorted correctly. Apple 1 is heavier than Apple 2? So is it heavier than the iPhone 3? We need to keep comparing until the sorting is completed. The Comparable interface can help us achieve this goal. Comparable itself cannot sort objects, but the method int compareTo(T) defined by the interface can.

How compareTo(T) works

Let’s get started by seeing which apple is heavier by using the compareTo() method.

Example 2

The compareTo() method works by returning an int value—either positive, negative, or zero. It compares objects by calling the object as argument. Negative numbers indicate that the object being called is "lighter" than the argument. If we were comparing apples by size, then the above call would return a negative number, such as -400, because red apples are smaller than green apples. If the two apples weigh the same, the call will return 0. If the red apple is heavier, compareTo() will return a positive number, such as 68.

Flexibility of compareTo()

If we call the compareTo() method above repeatedly, then we can sort by size, which is great, but not the end of the story. What if we want to sort apples by color? Or is it the weight? We can do it too. The point is, our client - let's call him Fat Farmer (see Example 3) - needs to define exactly how the apples need to be sorted before we start development.

Example 3

He can do this by answering these two questions:

  1. He How do you want Apple to sort? What characteristics does he want us to compare?

  2. In that context, what do "less than", "equal to" and "greater than" mean?

You can also use multiple features, which we will talk about later.

Example 1: Sorting Apples by Weight

In this first example, we will sort apples by weight. All it takes is one line of code.

Collections.sort(apples);
Copy after login

Example 4

The above line of code can do all the sorting work for us, as long as we define how to sort the apples in advance (this requires multiple lines of code).

Let’s start writing the apple category.

public class Apple implements Comparable {
    private String variety;
    private Color color;
    private int weight;
    @Override
    public int compareTo(Apple other) {
        if (this.weight < other.weight) {
            return -1;
        }
        if (this.weight == other.weight) {
            return 0;
        }
        return 1;
    }
}
Copy after login

Example 5

This is the first version of the Apple class. Since we are using the compareTo method and are sorting apples, I implemented the Comparable interface. In this first version, we compare objects by weight. In our compareTo() method, we write an if condition that says if this apple weighs less than the other apples, then a negative number is returned. To keep it simple, we assume it is -1. Remember, this means this Apple is lighter than Apple ‘other’. In the second if statement, we are stating that if the apples are equal in weight, then a 0 is returned. Of course, if this apple is neither lighter nor equally heavy, it can only be heavier than other apples. In this case we return a positive number, assumed to be 1.

例2:通过多个特征排序苹果

正如我前面提到的,我们还可以使用compareTo()比较多个特征。比方说,我们第一通过品种排序苹果,但如果两个苹果是同一品种,那么我们就按颜色排序。最后,如果这两个特性相同,那么我们将按重量排序。虽然我们可以手动实现这件事,就像我在最后一个例子中做的那样,但是其实可以用一种简洁得多的方式实现。一般来说,最好是重用现有的代码,而不是自己写。我们可以在Integer、String和枚举类中使用compareTo方法来比较值。由于我们没有使用Integer对象,用了int,所以我们不得不使用来自于Integer包装器类的一个静态的helper方法来比较两个值。

public class Apple implements Comparable {
    private String variety;
    private Color color;
    private int weight;
    @Override
    public int compareTo(Apple other) {
        int result = this.variety.compareTo(other.variety);
        if (result != 0) {
            return result;
        }
        if (result == 0) {
            result = this.color.compareTo(other.color);
        }
        if (result != 0) {
            return result;
        }
        if (result == 0) {
            result = Integer.compare(this.weight, other.weight);
        }
        return result;
    }
}
Copy after login

例6

在例6中,我们比较了客户指定的苹果的第一特性,它们的品种。如果compareTo()调用的结果为非零,那么我们返回值。否则,我们调用另一个compareTo()直到得到一个非零值,或者直到已经比较完这三个特征。尽管此代码可以工作,但它不是最有效或干净的解决方案。在例3中,我们重构我们的代码,使其更简单。

@Override
public int compareTo(Apple other) {
     int result = this.variety.compareTo(other.variety);
     if (result == 0) {
          result = this.color.compareTo(other.color);
     }
     if (result == 0) {
          result = Integer.compare(this.weight, other.weight);
     }
     return result;
}
Copy after login

例7

正如你所看到的,这大大减少了代码,并且每一次比较只要一行代码。如果一个compareTo()调用的结果是零,那么我们就转移到下一个相同if语句的比较中。顺便说一句,这是成为Clean Coder的一个很好的例子。通常情况下,你不需要立即写出干净的代码;你可以从一个粗略的想法开始,使其可以工作,然后不断改进,直到你尽可能得让它干净就可以了。

Comparable,hashCode以及Equals

你可能会注意到compareTo()看起来有点像hashCode()和equals()方法。但是,它们有一个重要的区别。对于hashCode()和equals()方法,比较个体属性的顺序不影响返回的值,但是,在compareTo()中,通过你比较对象的顺序来定义对象的顺序。

结论

在结论中我只想强调Comparable接口是多么的重要。它既用于java.util.Arrays,也用于java.util.Collections实用程序类,来排序元素和搜索排序集合中的元素。使用TreeSet和Tree Map,就更简单了——想要它们会自动排序必须实现Comparable接口的元素。

The above is the detailed content of Detailed explanation of sample code of Java Comparable interface. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template