Same point:
Comparable<t> and comparator<t> are all interfaces.
Different points:
There are different methods for declaring them. The former is the CompareTo () method, and the latter is the Compare () method.
Comparable<t> this interface is implemented by a specific class of practical significance, indicating what sort method the object of this class has. The following Apple
Public classAppleImplementsComparable<apple> { /*** Weight of apples*/ Private intweight; /*** Natural sort is small to large * returns 1, which means that this object is larger than the parameter object and is in the back, so you can control descending or ascending order*/@Override Public intCompareTo (Apple apple) {if( This. Weight >apple.getweight ()) { return-1; } Else if( This. Weight <apple.getweight ()) { return1; } Else { return0; } }
}
In the example above, Apple's light weight will be in the back, so it's sorted in descending order.
Comparator<t> This interface is typically used to define a comparer that is not implemented by a class that contains actual meaning, but rather by a specific comparer. The following defines a comparer:
Public classWeightcomparatorImplementsComparator<apple> { /*** Weight of apples*/ Private intweight; /*** Natural sort is from small to large * returns 1, which means this object is larger than the parameter object and is in front, so you can control descending or ascending order*/@Override Public intCompare (Apple A, Apple b) {if(A.getweight () >b.getweight ()) { return1; } Else if(A.getweight () <b.getweight ()) { return-1; } Else { return0; } } Public Static voidMain (string[] args) {Apple a=NewApple (); Apple b=NewApple (); Apple C=NewApple (); A.setweight (50); B.setweight (150); C.setweight (100); Apple[] Apples={A, B, c}; Arrays.sort (Apples,Newweightcomparator ()); // theSystem.out.println ("" + apples[0] + apples[1] + apples[2]); }}
The above example defines a weight comparator, which I use to compare the weight of an apple, i.e. using generics
public class Weightcomparator implements comparator<Apple>
Comparable<t> and Comparato<t>