ordering an array of objects in JavaBy Icycandy, at 2009/03/06 09:43:00
In the Java sorting seems not so convenient in C + +, search for a long time to see a lot of articles, probably are said to use arrays or ArrayList or list or collection, etc. to achieve, the most headaches is the source code to separate multiple files (this should be a good habit, However, the ACM only allows one source file to be submitted.
At the end of this article in accordance with the tips of gourd painting scoop, the source code in a file on it, for some less complex situation is very good.
Import Java.util.Arrays;
Import Java.util.Scanner;
Class Student implements comparable
{
String name;
int GPA;
public int compareTo (Object o)
{
Student s = (Student) o;
if (This.gpa = = S.gpa) return this.name.compareTo (s.name);
if (This.gpa < S.gpa) return-1;
else if (This.gpa = = S.gpa) return 0;
else return 1;
}
}
public class Test
{public
static void Main (string[] args)
{
Scanner in = new Scanner (system.in); C20/>int n = in.nextint ();
Student[] s = new Student[n];
for (int i = 0; I!= N; ++i)
{
S[i] = new Student ();
S[i].name = In.next ();
S[i].gpa = In.nextint ();
}
Arrays.sort (s);
for (Student ss:s)
{
System.out.println (ss.name);
System.out.println (SS.GPA);}}
For example, the input is:
4
Icycandy 40
Icycandy 50
Nicyun 40
Ybbaigo 50
The output is as follows:
The following items are taken to Javaapi:
Arrays.sort
Sort (object[] a)
Sorts the specified array of objects in ascending order, based on the nature of the elements. All elements in an array must implement the comparable interface. In addition, all elements in an array must be comparable (that is, E1.compareto (E2) should not throw classcastexception) for any E1 and E2 elements in the array.
Ensure that this sort is stable: the same elements are not reordered because the sort method is called.
The sorting algorithm is a modified merge sort algorithm that ignores merging if the highest element in the lower child list is less than the lowest element in the Taka list. This algorithm provides guaranteed N*log (n) performance.
Parameters:A-the array to sortThrown:ClassCastException-If the array contains elements that cannot be compared to each other (for example, strings and integers).Interface comparable<t> type parameters:T-Types of objects that can be compared with this objectall known sub-interfaces:Delayed, Name, Runnablescheduledfuture<v>, scheduledfuture<v>all known implementation classes: Authenticator.requestortype, bigdecimal, biginteger, boolean, Byte, ByteBuffer, calendar, character, Charbuffer, Charset, clientinfostatus, collationkey, Component.baselineresizebehavior, compositename, compoundname, date, Date, Desktop.Action, diagnostic.kind, Dialog.modalexclusiontype, dialog.modalitytype, Double, doublebuffer, DropMode, Elementkind, elementtype, enum, file, float, Floatbuffer, formatter.bigdecimallayoutform, formsubmitevent.methodtype, GregorianCalendar, GroupLayout.Alignment, intbuffer, integer, Javafileobject.kind, jtable.printmode, Keyrep.type, Layoutstyle.componentplacement, ldapname, long, longbuffer, mappedbytebuffer, MemoryType, Messagecontext.scope, modifier, multiplegradientpaint.colorspacetype, Multiplegradientpaint.cyclemethod, nestingkind, Normalizer.form, Objectname, objectstreamfield, Proxy.type, rdn, Resource.authenticationtype, RetentionPolicy, Roundingmode, Rowfilter.comparisontype, rowidlifetime, Rowsorterevent.type, Service.Mode, Short, shortbuffer, Soapbinding.parameterstyle, soapbinding.style, soapbinding.use, SortOrder, SourceVersion, sslengineresult.handshakestatus, sslengineresult.status, standardlocation, String, swingworker.statevalue, thread.state, time, timestamp, timeunit, TrayIcon.MessageType, typekind, uri, UUID, webparam.mode, xmlaccessorder, xmlaccesstype, XmlNsForm
Comparable<t>
This interface forces an overall ordering of the objects for each class that implements it. This sort is called the natural ordering of classes, and the CompareTo method of classes is called its natural comparison method.
The list of objects (and arrays) that implements this interface can be sorted automatically by Collections.sort (and Arrays.sort). An object that implements this interface can be used as a key in an ordered map or as an element in an ordered collection without specifying a comparer.
For each E1 and E2 of Class C, if and only if E1.compareto (e2) = 0 and E1.equals (E2) have the same Boolean value, the natural ordering of Class C is called consistent with equals. Note that NULL is not an instance of any class, even if E.equals (null) returns False,e.compareto (null), the NullPointerException is thrown.
Suggestions (though not required) are best to make natural sorting consistent with equals. This is because the behavior of an explicit comparer without an ordered set (and an ordered map) behaves "strangely" when you use elements (or keys) that are inconsistent with the natural sort and equals. In particular, such an ordered set (or an ordered map) violates the general contract of the set (or the mapping table) defined by the Equals method.
For example, if you add two keys A and B to an ordered set that does not use an explicit comparer (!a.equals (b) && A.compareto (b) = 0), the second add operation returns False (the size of the ordered set does not increase) because there are From the point of view of the order set, A and B are equal.
In fact, all Java core classes that implement comparable have a natural sort consistent with equals. Java.math.BigDecimal is an exception, and its natural sort treats BigDecimal objects (such as 4.0 and 4.00) whose values are equal, but with different precision, as equals.
Mathematically, the relational formula that defines the natural ordering of a given class C is as follows:
{(x, y) |x.compareto (y) <= 0}.
The whole sort of quotient is:
{(x, y) |x.compareto (y) = = 0}.
It follows the CompareTo agreement directly, the quotient is the equivalence relation of C, the natural sort is the whole sort of c. When it comes to the natural ordering of a class in accordance with equals, it refers to the equivalence relationship defined by the Equals (Object) method of the class.
{(x, y) |x.equals (y)}.
This interface is a member of the Java collections Framework.
start with the following version: 1.2 See also: Comparator
Method Summary |
Int |
CompareTo (T o) Compares the order of this object with the specified object. |
CompareTo CompareTo (T o)
Compares the order of this object with the specified object. If the object is less than, equal to, or greater than the specified object, it returns a negative integer, 0, or a positive integer, respectively.The implementation class must ensure that all x and Y have a sgn (X.compareto (y)) = =-SGN (Y.compareto (x)) relationship. (This means that if Y.compareto (x) throws an exception, X.compareto (Y) also throws an exception. )
The implementation class must also ensure that the relationship is transitive: (X.compareto (y) >0 && y.compareto (z) >0) means X.compareto (z) >0.
Finally, the implementation must ensure that X.compareto (y) ==0 means that for all z, SGN (X.compareto (z)) = = SGN (Y.compareto (z)) is present. Strongly recommended (X.compareto (y) ==0) = = (X.equals (y)) This approach, but is not strictly required to do so. In general, any class that implements the comparable interface and violates this condition should clearly point out this fact. This is recommended: "NOTE: This class has a natural ordering that is inconsistent with equals." ”
In the previous description, the symbol SGN (expression) specifies a Signum mathematical function that returns a value of 1, 0, or 1, depending on whether the expression value is negative, zero, or positive.
parameters: O-The object to compare. returns: a negative integer, 0, or a positive integer, depending on whether the object is less than, equal to, or greater than the specified object. Thrown: ClassCastException-If the type of the specified object does not allow it to be compared with this object
Icycandy
40
Nicyun
40
Icycandy
50
Ybbaigo
50
The following items are taken to Javaapi:
Arrays.sort
Sort (object[] a)
Sorts the specified array of objects in ascending order, based on the nature of the elements. All elements in an array must implement the comparable interface. In addition, all elements in an array must be comparable (that is, E1.compareto (E2) should not throw classcastexception) for any E1 and E2 elements in the array.Ensure that this sort is stable: the same elements are not reordered because the sort method is called.
The sorting algorithm is a modified merge sort algorithm that ignores merging if the highest element in the lower child list is less than the lowest element in the Taka list. This algorithm provides guaranteed N*log (n) performance.
parameter: a -array to sort Throw: classcastexception -If the array contains elements that cannot be compared to each other (for example, strings and integers). interface Comparable<t> type parameters: t -the types of objects that can be compared with this object all known sub-interfaces: delayed, name, runnablescheduledfuture<v> Scheduledfuture<v> All known implementation classes: Authenticator.requestortype, bigdecimal, BigInteger, boolean, byte, bytebuffer, calendar, character, , Charbuffer, clientinfostatus, collationkey, Component.baselineresizebehavior, compositename, CompoundName, date, date, desktop.action, diagnostic.kind, dialog.modalexclusiontype, Dialog.ModalityType , Double, doublebuffer, dropmode, elementkind, elementtype, enum,