Make writing a habit together! This is the 13th day of my participation in the “Gold Digging Day New Plan · April More Text Challenge”. Click here for more details.
⭐️ ⭐️
This article take you know Java common interface — Comparable, Comparator, Cloneable interface, Comparable, among them, the Comparator interface is a Comparator, which can be used to prioritize, object is to clone the interface Cloneable interface, Used to make a copy of an object.
📒 blog homepage: not seen flower smell blog homepage 🎉 welcome to pay attention to 🔎 like 👍 collect 🎉 🎉 message 📒 📆 Nuggets debut: 🌴 April 14, 2022 🌴 ✉️ Perseverance and hard work will be exchanged for poetry and distance! 💭 refer to books: 📚 “Java programming ideas”, 📚 “Java core technology” 💬 refer to online programming website: 📚 niuke.com SILVER force to deduct the code cloud of the blogger gitee, usually the program code written by the blogger are in it. Github of the blogger, the program code written by the ordinary blogger is in it. 🍭 author level is very limited, if you find mistakes, be sure to inform the author in time! Thank you, thank you!
1. com parable interface
1.1 Introduction: Array sort
We know that the ·sort method of the Arrays class sorts Arrays, such as integer Arrays:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {21.3.6.1.42.13.18.85.68}; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); }}Copy the code
Obviously we get an array sorted from smallest to largest, but in practice we often need to sort arrays of custom types. For example, I define a Person class:
class Person {
public int age;
public String name;
public int score;
public Person(int age, String name,int score) {
this.age = age;
this.name = name;
this.score = score;
}
@Override
public String toString(a) {
return "Person{" +
"age=" + age +
", name='" + name + '\' ' +
", score=" + score +
'} '; }}Copy the code
Let’s try it the same way:Error, because the compiler doesn’t know which element in the object you want to sort by, and that’s what you needComparable
This interface is used to sort custom types a bit like the Qsort function in C.
1.2 Using Camparable Interfaces
We’ll look at the source of the exception when we call sort:We found thatPerson
Strong turns are required to sortComparable
And callcompareTo
Method, which means that we need to be rightPerson
Class implementsComparable
Interface, and override in the interfacecompareTo
Methods.
public interface Comparable<T> {
public int compareTo(T o);
}
Copy the code
We found that the Comparable interface had only one method, compareTo, and a
after the Comparable interface, which is generic. It is equivalent to the parameters of a method and can be understood as a parameter to a type. When implementing the Comparable interface, you can simply pass in the type as if it were a method parameter, using <> like this:
class Person implements Comparable<Person>{
public int age;
public String name;
public int score;
public Person(int age, String name, int score) {
this.age = age;
this.name = name;
this.score = score;
}
@Override
public String toString(a) {
return "Person{" +
"age=" + age +
", name='" + name + '\' ' +
", score=" + score +
'} ';
}
@Override
public int compareTo(Person o) {
return this.age - o.age; }}Copy the code
Generics will be covered from shallow to deep in subsequent posts, but it’s easy to use them. For the compareTo method, whoever calls it is this. If the value returned is greater than 0, this is greater than O, equal to 0, and less than 0 means this is less than O. If you want a descending order, switch this and O.
@Override / / ascending
public int compareTo(Person o) {
return this.age - o.age;
}
@Override / / descending
public int compareTo(Person o) {
return o.age - this.age;
}
Copy the code
To compare strings or other classes, you need to call the compareTo method provided in the class, such as strings:
@Override
public int compareTo(Person o) {
return this.name.compareTo(o.name);
}
Copy the code
Similarly, reverse this and o in descending order. We’ve implemented the Comparable interface, so let’s see if we can sort successfully. Sort by age:
import java.util.Arrays;
class Person implements Comparable<Person>{
public int age;
public String name;
public int score;
public Person(int age, String name, int score) {
this.age = age;
this.name = name;
this.score = score;
}
@Override
public String toString(a) {
return "Person{" +
"age=" + age +
", name='" + name + '\' ' +
", score=" + score +
'} ';
}
@Override
public int compareTo(Person o) {
return this.age - o.age; }}public class Test1 {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Person(32."001".92);
people[1] = new Person(18."002".78);
people[2] = new Person(12."003".90); Arrays.sort(people); System.out.println(Arrays.toString(people)); }}Copy the code
Try the name againname
Sorting:
import java.util.Arrays;
class Person implements Comparable<Person>{
public int age;
public String name;
public int score;
public Person(int age, String name, int score) {
this.age = age;
this.name = name;
this.score = score;
}
@Override
public String toString(a) {
return "Person{" +
"age=" + age +
", name='" + name + '\' ' +
", score=" + score +
'} ';
}
@Override
public int compareTo(Person o) {
return this.name.compareTo(o.name); }}public class Test1 {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Person(32."zhang".92);
people[1] = new Person(18."wang".78);
people[2] = new Person(12."chen".90); Arrays.sort(people); System.out.println(Arrays.toString(people)); }}Copy the code
Okay, so these are the ones up hereComparable
Interface usage, we can see that the interface has a great disadvantage, that is to the class of highly intrusive, accidentally changedcompareTo
Method, the program does not report bugs, it is difficult to troubleshoot, so in practice often use comparatorComparator
, let’s have a chatComparator
.
2. com parator comparator
The Arrays class implements a number of sort methods to compare different types of data. Using the Comparator interface, you call whichever one you need.
public interface Comparator<T> {
int compare(T o1, T o2); . }Copy the code
Simply override the compare method to compare the size of the data type.
class AgeComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
returno1.age - o2.age; }}class NameComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
returno1.name.compareTo(o2.name); }}class ScoreComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
returno1.score - o2.score; }}Copy the code
If you want to do it in descending order, you can do the same thing with O1 and O2. How does that work? We can simply add a comparator object to the sort method after we instantiate the comparator object, because we have an overloaded sort method in the source code:
public static <T> void sort(T[] a, Comparator<? super T> c) {
if (c == null) {
sort(a);
} else {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a, c);
else
TimSort.sort(a, 0, a.length, c, null.0.0); }}Copy the code
Don’t need to understand how this method is implemented, just need to know that the second parameter of the method is the comparator, let’s see in practice.
public class Test {
public static void main(String[] args) {
Person[] people = new Person[3];
people[0] = new Person(32."wang".92);
people[1] = new Person(18."zhang".78);
people[2] = new Person(12."chen".90);
AgeComparator ageCmp = new AgeComparator();
NameComparator nameCmp = new NameComparator();
ScoreComparator scoreCmp = new ScoreComparator();
Arrays.sort(people, ageCmp);
System.out.println("In order of age:);
System.out.println(Arrays.toString(people));
Arrays.sort(people, nameCmp);
System.out.println("Sort by name:");
System.out.println(Arrays.toString(people));
Arrays.sort(people, scoreCmp);
System.out.println("In order of points:"); System.out.println(Arrays.toString(people)); }}Copy the code
No problem. Sorting succeeded. Comparator is much less intrusive and much more intuitive than Comparable. These two interfaces are common comparator tools in Java and will certainly be seen again in subsequent implementations of data structures. Finally, the Cloneable interface is the most commonly used tool for copying objects.
3.Cloneable Clone interface
The use of 3.1 Cloneable
First of all, this interface can help to generate a copy of the object, that is, to copy an object, in fact, its copy function is clone method, this interface is actually a signal that an object can be cloned (copy), why say? We go to see the source code of this interface you know, hee hee!
public interface Cloneable {}Copy the code
Oh my God, it’s an empty interface. You know, what’s an empty interface for? An empty interface serves as a flag, such as the Cloneable interface, which is a null interface that an object implements and that object (class) is tagged to indicate that the object (class) can be cloned. Let’s take a look at the Clone method that actually works:
protected native Object clone(a) throws CloneNotSupportedException;
Copy the code
This method is modified with the keyword native, indicating that it is implemented using C++ code and requires receiving exceptions when using it. The Cloneable interface is an empty interface, so you don’t need to override the Clone method. In this case, it’s a bit special. Even though the Cloneable interface is empty, you need to implement the Clone method.
class Person implements Cloneable {
int age;
public Person(int age) {
this.age = age;
}
@Override
public String toString(a) {
return "Person{" +
"age=" + age +
'} ';
}
@Override
protected Object clone(a) throws CloneNotSupportedException {
return super.clone(); }}public class Test {
public static void main(String[] args) {
Person p1 = new Person(18);
try {
Person p2 = (Person) p1.clone();
System.out.println(p1);
System.out.println(p2);
}catch (CloneNotSupportedException e) {
e.printStackTrace();
System.out.println("Abnormal clone!"); }}}Copy the code
I made a copy. These are the ones up hereCloneable
How to use an interface
3.2 Deep copy and Shallow copy
This depth copy simply say it, without examples, if you do not understand welcome to communicate with the blogger ~~.
Deep copy: When an object is copied, a new identical object is generated, and if there are other objects in the object, a new identical object is generated. This is called deep copy.
Shallow copy: When an object is copied, a new identical object is generated, but if there are other objects in the object, only the address of the object is copied, not a new object is generated.
First copy is for code implementation, depth method of copy not depth copy this one, if you just want to have a saying, given a copy of the method in the Java are shallow copy, although copies for simple data types can be said to be the deep copy, copy because simple data types cannot be reflected whether it is shallow or deep copy, When copying a reference type (such as an array or a string), it only copies the address of the object, and does not regenerate the object, so a single method copy can be understood as a shallow copy.
So whether a copy is a deep copy or a shallow copy depends on how the programmer implements the code, whether it’s a deep copy or a shallow copy.