Detailed explanation of sample code of Java Comparable interface
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:
He How do you want Apple to sort? What characteristics does he want us to compare?
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);
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; } }
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; } }
例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; }
例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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
