For
There are two ways to implement the sorting function. The basic types are not applicable here. The basic types are generally static methods in arrays.
1. If the object itself implements the comparable interface, instances of this class can be sorted.
About comparable: http://blog.csdn.net/treeroot/archive/2004/09/09/99613.aspx
As long as the comparable interface is implemented, you can call the collections sort method to sort the elements in the set.
2. Specify a comparator, that is, an instance that implements the comparator class.
However, Java only provides one comparator implementation, that is, collections. reverseorder ().
This method returns a reverse order that has implemented the comparable interface.
Let's take a look at all the content of comparator:
Public interface comparator {
Int compare (Object O1, object O2 );
Boolean equals (Object OBJ );
}
Two methods are defined. In fact, we only need to implement the compare method, because classes are inherited from objects by default.
Therefore, the equals method of the object is used.
Comparator is generally used as an anonymous class. For a set of objects that do not implement comparable
You need to specify a comparator.
Here is an example
For a comparable class, we use the simplest integer.
List list = new arraylist ();
List. Add (New INTEGER (3 ));
List. Add (New INTEGER (53 ));
List. Add (New INTEGER (34 ));
Collections. Sort (list );
If comparable is not implemented, we use objects to sort by hashcode.
List list = new arraylist ();
List. Add (new object ());
List. Add (new object ());
List. Add (new object ());
Collections. Sort (list, new comparator () {public int compare (Object O1, object O2 ){
Return (o1.hashcode ()-o2.hashcode ());
})
For map
Comparator Implementation Method
Class tcomp implements comparator {
Public int compare (Object A, object B ){
Int I, J, K;
String astr, BSTR;
Astr = (string);
BSTR = (string) B;
// Find index of beginning of last name
I = astr. lastindexof ('');
J = BSTR. lastindexof ('');
K = astr. substring (I). compareto (BSTR. substring (j ));
If (k = 0) // last names match, Check entire name
Return astr. compareto (BSTR );
Else
Return K;
}
}
Public class treemapsort {
Public static void main (string [] ARGs ){
Treemap TM = new treemap (New tcomp ());
TM. Put ("John Doe", new double (3434.34 ));
TM. Put ("Tom Smith", new double (123.22 ));
TM. Put ("Jane Baker", new double (1378.00 ));
TM. Put ("Todd Hall", new double (99.22 ));
TM. Put ("Ralph Smith", new double (-19.08 ));
System. Out. println (TM. tostring ());
}
}