Comparable Interface

Unlike C++, operator  / == can be overloaded by user, so those symbol expended its usage to other user-defined class / object. As long as overload is set then compiler won’t complain during compiling time.

However it really draw my attenuation that how the same thing could be achieved on Java platform?  Especially on certain case like: Java collection is used (List / Stack…….). One thing clear is that user is not able to alter how the data structure compare within the set.

By googling and search related article on stack overflow. Realise that collection is rely on Comparable interface for sorting. So theoretically speaking, developer can implement Comparable on class. Then by time when collection need to be sort, sorting method would have internal call for comparable in order to maintain the whole into correct order.

Following is the example that I wrote by implement the comparable interface for demonstration. Hope it would help gain more insight of the concept.
First talk about the class itself, it representing a laptop with Brand / Processing Power / Weight.
And by adopting the comparable interface, first the incoming type need to be declared. So the run-time can know which specific type allow for comparison.

The following line of code clearly show that the interface only on type . It means that the interface won’t work while Lappy is comparing with type other than Lappy.
Here is the main body of the method, in this example the method would first compare computing power in ascendent order, only compare weight by having equal computing power.
Again, two lappy object are constructed and add into list accordingly. The default order would { Mac_air, Ms_surface }. However by the time list.sort () called, the order would changed to {Ms_surface, Mac_air }.


Source code is available on my Git hub account (All about Java) repo.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s