why do we need Icomparable interface?

244 views Asked by At

Please clarify, we can have our own method to compare two objects instead implementing interface.Also what is the significance of interfaces?

2

There are 2 answers

0
this. __curious_geek On

Because when some other api/code (other than yours) wants to compare your custom objects/types, then, IComparable will provide them the implementation of comparison regardless of what your objects are. They will simply check if your object implements IComparable and if it does then it will invoke the comparison and sort them. Some scenarios like, When you have your custom object list bound to a grid then when you click on Header of coloumn to sort the objects, then grid will do the sorting by comparison.

0
Prescott On

Significance of interfaces:

Yes, you can have your own method to comppare two objects instead of implementing an interface. However, the interface allows for greater flexibility. For example, suppose you have a list of your objects. If you call list.sort() it would use the compare interface provided - if you don't provide this you will get unexpected results.