❤ Write in front
❤ Blog home page: Hard working Naruto
❤ Series column: Java basic learning 😋
❤ Welcome, friends, praise 👍 follow 🔎 Collection 🍔 Learning together!
❤ If there are mistakes, please correct them! 🌹
1, Two ways of sorting objects in Java
In Java, the sorting of object arrays is often involved, so the comparison between objects is mentioned
● natural sorting: Java lang.Comparable
● customized sorting: Java util. Comparator
2, Method 1: natural sorting
java.lang.Comparable
- Definition: the Comparable interface forcibly sorts the objects of each class that implements it as a whole
- Content: the class implementing Comparable must implement the compareTo(Object obj) method. The size of the two objects is compared through the return value of the compareTo(Object obj) method
- Result: if the current object this is greater than the parameter object obj, a positive integer is returned; if the current object this is less than the parameter object obj, a negative integer is returned; if the current object this is equal to the parameter object obj, zero is returned
- give an example:
class Goods implements Comparable { private String name; private double price; public Goods(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "name='" + name + '\'' + ", price=" + price + '}'; } //Compare the size of the goods according to the price @Override public int compareTo(Object o) { if (o instanceof Goods) { Goods other = (Goods) o; if (this.price > other.price) { return 1; } else if (this.price < other.price) { return -1; } return 0; } throw new RuntimeException("The data type entered is inconsistent"); } }
- Create the ComparableTest class to test:
import java.util.Arrays; public class ComparableTest { public static void main(String[] args) { Goods[] all = new Goods[4]; all[0] = new Goods("<A dream of Red Mansions", 100); all[1] = new Goods("<Journey to the West", 80); all[2] = new Goods("<Romance of the Three Kingdoms", 140); all[3] = new Goods("<Outlaws of the marsh", 120); Arrays.sort(all); System.out.println(Arrays.toString(all)); } }
- The result is:
[Goods{name='<Journey to the West', price=80.0}, Goods{name='<A dream of Red Mansions', price=100.0}, Goods{name='<Outlaws of the marsh', price=120.0}, Goods{name='<Romance of the Three Kingdoms', price=140.0}]
🔥 Typical implementation of Comparable
(from small to large)
- String: compare according to the Unicode value of the characters in the string
- Character: compare according to the Unicode value of the character, the wrapper class corresponding to the numeric type, BigInteger and BigDecimal: compare according to their corresponding numeric size
- Boolean: the wrapper class instance corresponding to true is greater than that corresponding to false
- Date, Time, etc.: the later date and Time is greater than the previous date and Time
🎁 Note: objects that implement the Comparable interface can use collections Sort or arrays Sort for automatic sorting
3, Method 2: customized sorting
java.util.Comparator
- Situation: when the element type does not implement the Comparable interface and it is inconvenient to modify the code, or implements the Comparable interface but the sorting rules are not suitable for the current operation, you can consider sorting with the Comparator object to force the comparison of the overall sorting of multiple objects
- Results: rewrite the compare(Object o1,Object o2) method to compare the sizes of o1 and o2: if the method returns a positive integer, o1 is greater than o2; If 0 is returned, it means equal; Returns a negative integer indicating that o1 is less than o2
- For example, it is the same as in mode 1 and is omitted here;
Create ComparatorTest class to test: (compare initials)
import java.util.Arrays; import java.util.Comparator; public class ComparatorTest { public static void main(String[] args) { Goods[] all = new Goods[4]; all[0] = new Goods("War and Peace", 100); all[1] = new Goods("Childhood", 80); all[2] = new Goods("Scarlet and Black", 140); all[3] = new Goods("Notre Dame de Paris", 120); Arrays.sort(all, new Comparator() { @Override public int compare(Object o1, Object o2) { Goods g1 = (Goods) o1; Goods g2 = (Goods) o2; return g1.getName().compareTo(g2.getName()); } }); System.out.println(Arrays.toString(all)); } }
- Operation results:
[Goods{name='Childhood', price=80.0}, Goods{name='Notre Dame de Paris', price=120.0}, Goods{name='Scarlet and Black', price=140.0}, Goods{name='War and Peace', price=100.0}]
4, Comparison of the two methods
Once the method of the Comparable interface is determined, ensure that the objects of the implementation class of the Comparable interface can be compared in size at any position, and the Comparator interface is a temporary comparison
👌 The author is a Java beginner. If there are errors in the article, please comment and correct them in private letters and learn together~~
😊 If the article is useful to the friends, praise it 👍 follow 🔎 Collection 🍔 Is my biggest motivation!
🚩 Step by step, nothing to a thousand miles, book next time, welcome to see you again 🌹