Pages

10.26.2013

Java Comparator vs Comparable

The Comparable and Comparator interface both let objects in Java be sorted, but go about it in different ways. Let's say that you are a sort method, and I pass you a collection of beer. Using comparable (built into the beer) you can sort the beer by name. Duh, it's on the bottle.

But what if I ask you to sort my beer by temperature, coldest first? I would need to provide you with a tool (a comparator) , in this case, an infrared temperature sensor in order for you to accomplish the task. Using the temperature sensor I've provided you, it's now possible to sort the beer by temperature.

Similarly, if I asked you to sort beer by alcohol content, I would need to give you a hydrometer to check the specific gravity. This is akin to yet another comparator. Notice that none of these comparators are built into the beer itself.

Have a look at an example I've whipped up. Download the files from drive and compile them using javac *.java on your machine. Then run the one called BeerFridge.java using the command java BeerFridge

No comments: