[Common Java class libraries] _ notes on comparator (comparable and comparator)

Source: Internet
Author: User

[Common Java class libraries] _ notes on comparator (comparable and comparator)

Objectives of this chapter:
Understanding the use of comparable comparison Interfaces
Understand the basic sorting principle of Comparator
Understanding the use of comparator comparison Interfaces

Comparable Interface

You can directly use the java. util. arrays class to sort arrays. However, the class where the object is located must implement the comparable interface to specify the sorting interface.

The comparable interface definition class is as follows:

Public interface comparable <t> {
Public int compareto (t o );
}
This method returns an int type of data, but the int value can only be of the following three types:

1: greater
-1: indicates that the value is smaller
0: equal

Instance code:

Class student implements comparable <student> {private string name; private int age; private float score; Public student (string name, int age, float score) {This. name = Name; this. age = age; this. score = score;} Public String tostring () {return name + "\ t" + this. age + "\ t" + this. score;} public int compareto (student Stu) {If (this. score> Stu. score) {return-1;} else if (this. score <Stu. score) {return 1;} else {If (this. age> Stu. age) {return 1;} else if (this. age <Stu. age) {return-1 ;}else {return 0 ;}}} public class comparabledemo01 {public static void main (string ARGs []) {student STU [] = {New Student ("Zhang San", 20, 990000f), new student ("Li Si", 22, 90.0f), new student ("Wang Wu ", 22,100.0 f)}; Java. util. arrays. sort (Stu); // sort (INT I = 0; I <Stu. length; I ++) {// loop output array content system. out. println (STU [I]) ;}}

Note: If the student class does not implement the comparable interface at this time, the following exception occurs during execution.

Exception in thread "Main" Java. Lang. classcastexception:

3.2 sorting principle of analysis comparator:

In fact, we often hear about the binary tree sorting method in the data structure. We sort the binary tree, and then read the content in sequence by means of sequential traversal.

The central traversal first traverses the left subtree, then accesses the root node, and finally traverses the right subtree. When traversing the left and right subtree, we still traverse the left subtree first, then access the root node, and finally traverse the right subtree.


The following describes how to manually implement a binary tree comparison algorithm.
For the operation method, the integer class is used here.

Public class comparabledemo02 {public static void main (string ARGs []) {comparable COM = NULL; // declare a comparable interface object COM = 30; // instantiate System for comparable through integer. out. println ("content:" + COM); // The tostring () method is called }};

After learning about this feature, we can complete a binary tree algorithm.

Class binarytree {class node {// declare a node class private comparable data; // Save the specific content private node left; // Save the left subtree private node right; // Save the public node (comparable data) {This. data = data;} public void addnode (node newnode) {// determine whether to place the node in the left subtree or right subtree if (newnode. data. compareto (this. data) <0) {// small content, placed in the left subtree if (this. left = NULL) {This. left = newnode; // directly set the new node to the left subtree} else {This. left. addnode (newnode); // continue to judge down}} If (newnode. data. compareto (this. data)> = 0) {// place it in the right subtree if (this. right = NULL) {This. right = newnode; // if there is no right subtree, set this node to the right subtree} else {This. right. addnode (newnode); // continue downward judgment }}} public void printnode () {// when outputting, traverse if (this. left! = NULL) {This. Left. printnode (); // output left subtree} system. Out. Print (this. Data + "\ t"); If (this. Right! = NULL) {This. right. printnode () ;}}; private node root; // The root element public void add (comparable data) {// Add the Element Node newnode = new node (data ); // define a new node if (root = NULL) {// No root node root = newnode; // The first element serves as the root node} else {root. addnode (newnode); // determine whether to put it in the left subtree or right subtree} public void print () {This. root. printnode (); // output through the root node}; public class comparabledemo03 {public static void main (string ARGs []) {binarytree bt = new binarytree (); BT. add (8); BT. add (3); BT. add (3); BT. add (10); BT. add (9); BT. add (1); BT. add (5); BT. add (5); system. out. println ("sorted Result:"); BT. print ();}};

3.3. Another comparator: Comparator

Paste the Code directly:

Import Java. util. *; class student {// specify the type as student private string name; private int age; Public student (string name, int age) {This. name = Name; this. age = age;} public Boolean equals (Object OBJ) {// override the equals method if (this = OBJ) {return true;} If (! (OBJ instanceof student) {return false;} student Stu = (student) OBJ; If (Stu. name. equals (this. name) & Stu. age = This. age) {return true;} else {return false;} public void setname (string name) {This. name = Name;} public void setage (INT age) {This. age = age;} Public String getname () {return this. name;} public int getage () {return this. age;} Public String tostring () {return name + "\ t" + this. age ;}}; class studentcomparator implements comparator <student >{// implement the comparator // because the equals () method public int compare (student S1, student S2) {If (s1.equals (S2) {return 0;} else if (s1.getage () <s2.getage () {// return 1 by age ;} else {return-1 ;}}; public class comparatordemo {public static void main (string ARGs []) {student STU [] = {New Student ("James ", 20), new student ("Li Si", 22), new student ("Wang Wu", 20), new student ("Zhao Liu", 20 ), new student ("Sun Qi", 22)}; Java. util. arrays. sort (STU, new studentcomparator (); // sort (INT I = 0; I <Stu. length; I ++) {// cyclically output the content in the array system. out. println (STU [I]) ;}}};

Related Article

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.