473,406 Members | 2,259 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

IComparable vs IComparer ?

Hello,

Could someone please explain me the difference between the 2 interfaces
IComparable and IComparer ?

In which cases use one or the other ?
Are they dedicated to own classes or built-in collections ?
Regards,
Cybertof.
Nov 15 '05 #1
3 30153
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Any class that implements IComparable is *comparable*. That is, you can
compare an instance of that class with another instance in a manner that
you define.

OTOH, a class that implements IComparer is a... well, a comparer (Java
people call this a Comparator), i.e.: a class that imposes ordering on a
set of objects.

When you want to sort an unsorted array of objects of the same class,
you can either make the class implement IComparable, or you can
implement IComparer in a separate class, and pass that to Array.Sort().
Of course if the comparison is done based on a *private* member of the
class, IComparable is more appropriate, since having your IComparator
implementation be able to access its private members may not be
possible/appropriate.

Cybertof wrote:

| Hello,
|
| Could someone please explain me the difference between the 2 interfaces
| IComparable and IComparer ?
|
| In which cases use one or the other ?
| Are they dedicated to own classes or built-in collections ?
|
|
| Regards,
| Cybertof.

- --
Ray Hsieh (Ray Djajadinata) [SCJP, SCWCD]
ray underscore usenet at yahoo dot com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (MingW32)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQE/oPDWwEwccQ4rWPgRAms1AJ9esPvldfXz4pvHKPpiNOiBrYopNA CfTnE3
zGByXZQQK28+E1QSoXM8lXE=
=ruXq
-----END PGP SIGNATURE-----

Nov 15 '05 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

private *and* not (supposed to be) exposed in any way to other classes,
I mean :)

Ray Hsieh (Ray Djajadinata) wrote:

| Of course if the comparison is done based on a *private* member of the
| class, IComparable is more appropriate, since having your IComparator
| implementation be able to access its private members may not be
| possible/appropriate.

- --
Ray Hsieh (Ray Djajadinata) [SCJP, SCWCD]
ray underscore usenet at yahoo dot com
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (MingW32)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQE/oPIGwEwccQ4rWPgRAgsyAKCAbfnWGoY7kZGpxbvVLaCn436VUg CdEBxr
x9YGirhTd8L8lZxCWEVbuF4=
=PGvj
-----END PGP SIGNATURE-----

Nov 15 '05 #3
They have a variety of uses, but perhaps the most common is in sorting an
ArrayList.

Suppose you have a class Dog, and an ArrayList, List, of Dogs. You wish to
sort List by ageOfDog. You would have Dog implement the interface
IComparable. The implementation would cast the parameter in the CompareTo
method to a Dog, and return a value based on how this.ageOfDog compared to
((Dog)(obj)).ageOfDog). Then to sort the List, you could just invoke
List.Sort().

But suppose in another part of the application you would like to sort the
same List by nameOfDog. You have already "used up" the IComparable
interface that Sort uses. So, you can either set up a new class that
inherits from IComparer, or (if this is the only additional sort you need),
have Dog implement the IComparer interface too.
Then in the Compare method, which has two parameters, you would cast each to
a Dog and return a value based upon how the nameOfDog compares. Then to
invoke a sort by nameOfDog you would just say List.Sort(this) (or
List.Sort(someObjectThatImplementsIComparer)).

So: use IComparable when you want one of the objects in the comparison to
handle the compare. Use IComparer when this is not feasible or desirable,
and either you need to let a third object handle the compare, or want to do
different compare logic than has been already been used by IComparable.

Sort is not the only method that uses these interfaces (e.g. BinarySearch).
You may wish to invoke them yourself if you write a general routine that
needs to compare objects but wish to leave the details of the comparison up
to another object.
"Cybertof" <cy****************@gmx.net> wrote in message
news:MP************************@msnews.microsoft.c om...
Hello,

Could someone please explain me the difference between the 2 interfaces
IComparable and IComparer ?

In which cases use one or the other ?
Are they dedicated to own classes or built-in collections ?
Regards,
Cybertof.

Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Fernando Rodríguez | last post by:
Hi, I don't understand very well the diferences between both. When should each be used? Thanks
2
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to...
1
by: Brett Romero | last post by:
What are the reasons to use one over the other? SortedList implements IComparer.Compare(). Why would you also want to create a SortedList class that implements IComparable.CompareTo()? I know...
1
by: Steph | last post by:
Hello, i dot not manage to write the code to sort a array on multiple columns. ArrayList people = new ArrayList(); people.Add(new Person("John", "Doe", 76)); people.Add(new Person("Matt", "Dire",...
8
by: SimeonArgus | last post by:
I need to sort a list of points, so I've considered using an IComparable implementation. Should be easy, right? But I need to know two things in the CompareTo function, not one. Test1: I need to...
1
by: Stephen.Schoenberger | last post by:
Hello, I am trying to figure out how to make an IComparable Byte Array Comparison class in C# and keep running into dead ends. I have read where this isn't possible and have seen a few hints...
2
by: soni2926 | last post by:
hi, I have a class called orders, which has a DateTime dateCreated property, telling me when each order was created. I get the orders returned to me in a collection, as an array. but now i need...
1
by: =?Utf-8?B?U2FsYW1FbGlhcw==?= | last post by:
Hi, I am creating an array of performancecounter objects and wondering if it is possible to sort this array according to category Names. I tried Array.Sort(AllCountersCategories) but it is...
1
by: Mitch | last post by:
I have several classes that inherit other classes. I need to be able to sort the Mesh class based on its inherited list of Poly.ZMax,. How do I use IComparer or IComparable to achieve this? ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.