Javase Introductory Learning 39:java Set frame Comparator

Source: Internet
Author: User

Sorting algorithm is our most commonly used algorithm, beginner program, everyone has tried to sort. But it's just limited to a simple sort.

If the following numbers are sorted

1,3,5,8,3,6

So we came to the end

1,3,3,5,6,8

Sort the following letters (characters)

A,i,e,f,w,s

So we came to the end

a,e,f,i,s,w

But the situation we have is not so simple. In order to sort the products in the company, it is very easy to think of the sort of goods by their names.

It's over, and it's simple and clear. But the reality is as simple as we believe. The same product name can have different batches, the arrival time, may also have the unit price

The difference. Obviously it is unreasonable to sort by the name of the commodity.

There are two types of Java comparators, namely the comparable interface and the comparator interface. When sorting an array of objects, the role of the comparator is not

Often obvious.

One comparable interface--comparable interface

Comparable implement this interface hint: the instance of this class can compare size, can be natural sort, define the default comparison rule.

The comparable interface forces the overall ordering of objects that implement each of its classes. This sort is called the natural ordering of the class, the CompareTo of the Class ()

method is referred to as its natural comparison method.

Objects that implement this interface can be automatically sorted by Collections.sort () and Arrays.sort (), or they can be used as keys or ordered collections in an ordered map

You do not need to specify a comparer.

The CompareTo () method returns a positive number representing a large, negative number that is small, and 0 for equality.

Comparable interface-defined methods:


Interface declaration:

<span style= "FONT-SIZE:18PX;" >public interface comparable<t>{          int compareTo (T o);  } </span>

Two comparator interface--Comparator interface

The comparator interface is used to define temporal comparison rules instead of the default comparison rules. Comparator can be passed to the sort () method, allowing

achieve precise control over the sort order. You can also provide sorting for objects that do not have a natural order of collection.

The comparator interface compares the two parameters used to sort. Returns a negative integer, 0, or as the first parameter is less than, equal to, or greater than the second parameter, respectively

A positive integer.

Comparator interface Method:


Interface declaration:

<span style= "FONT-SIZE:18PX;" >public interface comparator<t>{          int compare (t O1, T O2);       } </span>

three examples

All classes that can be sorted implement the Java.lang.Comparable interface, and the comparable interface has only one method CompareTo (Object

obj), the method: returns 0 for this=obj; Returns an integer indicating that this>obj; returns a negative number for this<obj. Implements the class of the comparable interface through

Implement the CompareTo () method to determine how the class objects are sorted.

(1) using the comparable interface

Let the class that needs to be sorted implement the comparable interface, overriding the CompareTo (T O) method in which the collation is defined, then you can

Call Collections.sort () directly to sort the collection of objects, with the following example:

<span style= "FONT-SIZE:18PX;" >import java.util.*;p ublic class test{public static void Main (string[] args) {List L1 = new ArrayList (); L1.add (New Name ( "Karl", "M")), L1.add (new name ("Steven", "Lee")), L1.add ("John", "O"), L1.add (new name ("Tom", "M"));//Sort before traversing for (Object o:l1)                {System.out.println (o); }//sort Collections.sort (L1);                System.out.println ("---------------");//Sort After to traverse for (Object o:l1) {System.out.println (o); }}}class name implements Comparable{private string Firstname;private string Lastname;public Name (String firstName, String lastName) {this.firstname = Firstname;this.lastname = LastName;} Public String Getfirstname () {return firstName;} Public String Getlastname () {return lastName;} Public String toString () {return firstName + "" +lastname;} public boolean equals (Object obj) {if (obj instanceof name) {name name = (name) Obj;return (Firstname.equals (name.firstname ) && (Lastname.equals (Name.lastname));} Else{returnSuper.equals (obj);}} public int hashcode () {return Firstname.hashcode ();} public int compareTo (Object o) {name n = (Name) o;int lastcmp = Lastname.compareto (N.lastname); return (lastcmp!=0?lastcmp: Firstname.compareto (N.firstname));}} </span>

Operation Result:


(2) using the comparator interface

If you are familiar with Java, you will know the Java.util.Comparator interface. To implement the function inside the int compare (object O1, Object O2) returns

Back to a base type of integral type, a negative number indicates that O1 is less than O2, return 0 means O1 and O2 are equal, and a positive number indicates O1 is greater than O2.

Give a simple example and then use the program to implement it. If the company wants to sort the employees (not the leader in front), let's say our requirements are more complex. First

The surname is sorted, whose surname Pinyin leans forward, who is in front of the platoon. The names are then sorted. Well, if you have the same name, women are ahead. If the name and gender are

The same, the youngest platoon head. OK, one is not a complex requirement.

Examples of online cases have been rewritten:

So we designed the personnel class to have a few variables, firstname,lastname,sex,age, respectively, the surname, name, gender, age. Person.java

Source file Code:

<span style= "FONT-SIZE:18PX;" >public class Person {    String firstname,lastname;      Boolean sex;      Integer age;      Public person (String firstname,string Lastname,boolean Sex,integer age) {this.firstname = FirstName;          This.lastname = LastName;          This.sex = sex;          This.age = age;      }      Public String Getfirstname () {          return firstname;      }        Public String Getlastname () {          return lastname;      }      Public Boolean Getsex () {          return sex;      }        Public Integer Getage () {          return age;      }         For ease of input, the ToString () public      String ToString () {          return firstname + "" +lastname+ "" + (Sex.booleanvalue ()) was rewritten. Male ":" female ") +" "+age;      }  }  </span>

Here is the Comparators.java source file code to implement the comparator:

<span style= "FONT-SIZE:18PX;" >import java.util.*;p ublic class Comparators{public static Java.util.Comparator Getcomparator () {return new Java.util.Comparator () {public int compare (object O1, Object O2) {if (O1 instanceof String) {return compare ((String) O1, (                  String) O2);                  }else if (O1 instanceof Integer) {return compare ((integer) O1, (integer) O2);                  }else if (O1 instanceof person) {return compare (person) O1, (person) O2);                  }else {System.err.println ("no suitable comparator found");        return 1;                  }} public int compare (string O1, String O2) {string S1 = (string) O1;                  String s2 = (string) O2;                  int len1 = S1.length ();                  int len2 = S2.length ();                  int n = math.min (len1, len2);                  Char v1[] = S1.tochararray ();                  Char v2[] = S2.tochararray (); Intpos = 0;                      while (n--! = 0) {char C1 = V1[pos];                      char C2 = V2[pos];                      if (c1! = C2) {return c1-c2;                  } pos++;              } return len1-len2;                  } public int Compare (integer o1, integer o2) {int val1 = O1.intvalue ();                  int val2 = O2.intvalue ();              Return (Val1 < Val2 1: (Val1 = = val2? 0:1));              } public int Compare (Boolean O1, Boolean O2) {return (O1.equals (O2)? 0: (O1.booleanvalue () ==true?1:-1));                  } public int Compare (person O1, person O2) {String firstname1 = O1.getfirstname ();                  String firstname2 = O2.getfirstname ();                  String lastname1 = O1.getlastname ();                  String lastname2 = O2.getlastname ();                  Boolean sex1 = O1.getsex ();                  Boolean sex2 = O2.getsex (); Integer Age1 = O1.getage ();                  Integer age2 = O2.getage ();  Return (compare (firstname1, firstname2) = = 0? (Compare (lastname1, lastname2) = = 0? (Compare (sex1, sex2) = = 0? (Compare (Age1, age2) = = 0? 0:compare (age1, age2)): Compare (Sex1, sex2)): Compare (L              Astname1, lastname2)): Compare (Firstname1, firstname2));      }        }; }} </span>

Test:

<span style= "FONT-SIZE:18PX;" >import java.util.*;p ublic class test{public static void Main (string[] args) {List L1 = new ArrayList (); L1.add (New Perso N ("Ouyang", "Feng", Boolean.true, New Integer));                L1.add (New person ("Zhuang", "GW", Boolean.true, New Integer));                 L1.add (New person ("Zhuang", "GW", Boolean.false, New Integer));                L1.add (New person ("Zhuang", "GW", Boolean.false, New Integer (2)));                for (Object o:l1) {                     System.out.println (o);}                Collections.sort (L1, Comparators.getcomparator ());          System.out.println ("---------------");                for (Object o:l1) {                     System.out.println (o);}    }   }  </span>

Operation Result:



Javase Introductory Learning 39:java Set frame Comparator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.