Object comparison and sorting (3): Implementing icomparable and icomparer generic Interfaces

Source: Internet
Author: User

1: Concepts of comparison and sorting

 

Comparison: compare two object classes by>, =, <.

 

Sort: In the collection class, sort the objects in the Collection class. Sort basedAlgorithmComparison functions provided by object classes.

 

The basic types all provide the default comparison algorithm. For example, string provides the comparison by letter, and INT provides the comparison by integer size.

2: icomparable and icomparer

The two interfaces have been described in the previous log. Now I will explain them again with one instance.

When we create our own entity classes, such as student, we want to sort them by age by default, we need to implement the icomparable interface for the object class.

ClassStudent: icomparable
{
Public StringName {Get;Set;}
Public IntAge {Get;Set;}

# Region icomparable members

Public Int Compareto ( Object OBJ)
{
Student = OBJ As Student;
If (Age> Student. Age)
{
Return 1;
}
Else If (Age = student. Age)
{
Return 0;
}
Else
{
Return -1;
}
// Return age. compareto (student. Age );
}
# Endregion
}

 
PS: Pay attention to the aboveCodeThe compareto method in has an annotation code. In fact, this function can be replaced by this annotation code because it uses the default comparison method of integer. This annotation code is not used here to better illustrate the working principle of the comparator.

 
Next, write a test case:

         Public Form1 ()
{
Initializecomponent ();
Studentlist =New Arraylist ();
Studentlist. Add ( New Student () {age = 1, name =" A1 "});
Studentlist. Add ( New Student () {age = 5, name =" G1 "});
Studentlist. Add ( New Student () {age = 4, name =" B1 "});
Studentlist. Add ( New Student () {age = 2, name =" F1 "});
}
Arraylist studentlist;
Private Void Button#click ( Object Sender, eventargs E)
{
Studentlist. Sort ();
Foreach (Student item In Studentlist)
{
This . Textbox1.text + = item. Name +" ---- "+ Item. Age. tostring () +"\ R \ n ";
}
}

 

Running result:

 

A1 ---- 1
F1 ---- 2
B1 ---- 4
G1 ---- 5

 

OK. The question is displayed. What should I do if I don't want to use age as the comparator. At this time, the role of icomparer is coming,You can use icomparer to implement a custom comparator.. As follows:

 

 
ClassSortname: icomparer
{
 
Public static icomparer default = new personcomparername ();

# Region icomparer members

Public IntCompare (ObjectX,ObjectY)
{
Student S1 = xAsStudent;
Student S2 = yAsStudent;
ReturnS1.name. compareto (s2.name );
}

# Endregion
}

 

In this case, we provide this comparator for the sort method in sorting:

 

Studentlist. Sort (sortname. Default );

 

The running result is:

 

A1 ---- 1
B1 ---- 4
F1 ---- 2
G1 ---- 5

The previous diary has already said,

Generally, we use icomparable to provide the default comparison code of the class, and use other classes to provide non-default comparison code.

In the preceding example, the default comparison code (icomparable) is provided in student, so we can sort it by. Sort.

At the same time, we can also provide non-default comparison code, such as sortname In the example (the icomparer interface is required), so we can sort by. Sort (sortname. Default.

As long as the implementation is an icomparer interface, it can be used as a comparator parameter and thrown to sort ().

3: icomparable and icomparer generic implementation icomparable <t> and icomparer <t>

 

If we have a little experience, we will find that the above Code uses a collection class arraylist that is not recommended. When generics are available, we recommend that you do not use all non-generic collection classes as much as possible. As for the reason, we can also see some clues from the above Code.

 

Check the Compare function, for example:

 

 
Public IntCompare (ObjectX,ObjectY)
{
Student S1 = xAsStudent;
Student S2 = yAsStudent;
ReturnS1.name. compareto (s2.name );
}

We found that this function is packed and unpacked. This will affect the performance. If our set contains thousands of complex entity objects, the performance consumed during sorting is objective. The appearance of generics can avoid unpacking and packing.

 

Therefore, the arraylist in the above Code should be replaced by list <t>.This implementation is icomparable <t> and icomparer <t>.The final code should be like:

 

 Public Partial Class Form1: Form
{
Public Form1 ()
{
Initializecomponent ();
Studentlist = New List <student> ();
Studentlist. Add ( New Student () {age = 1, name =" A1 "});
Studentlist. Add ( New Student () {age = 5, name =" G1 "});
Studentlist. Add ( New Student () {age = 4, name =" B1 "});
Studentlist. Add ( New Student () {age = 2, name =" F1 "});
}
List <student> studentlist;
Private Void Button#click ( Object Sender, eventargs E)
{
Studentlist. Sort ( New Sortname ());

Foreach (Student item In Studentlist)
{

This . Textbox1.text + = item. Name +" ---- "+ Item. Age. tostring () +" \ R \ n ";
}
}
}

Class Student: icomparable <student>
{
Public String Name { Get ; Set ;}
Public Int Age { Get ; Set ;}

# Region icomparable <student> Members

Public Int Compareto (student other)
{
Return Age. compareto (other. Age );
}

# Endregion
}

Class Sortname: icomparer <student>
{
# Region icomparer <student> Members

Public Int Compare (student X, student y)
{
Return X. Name. compareto (Y. Name );
}

# Endregion
}
Through the above example, we can know that implementing generic interfaces can make the code more concise.

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.