InterviewSolution
| 1. |
What is the difference between Comparable and Comparator interface? |
Answer»
A comparable object is capable of comparing itself with another object. The class itself must implement the java.lang.Comparable interface to COMPARE its instances. Comparable has compareTo(Object o) to sort the objects Consider a Product class that has members like, productId, productName, ManufacturerYear. Suppose we wish to sort a LIST of Products based on year of productId. We can implement the Comparable interface with the Product class, and we override the method compareTo() of Comparable interface.
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface. Comparator has compare(Object o1, Object o2) to sort the objects. class Product implements Comparable<Product> { private int productRating; private String productName; private int mfgYear; private double price; // USED to sort movies by mfgYear public int compareTo(Product pr) { return this.mfgYear - pr.mfgYear; } // Constructor public Product(int pr, String pn, int mY, double price) { this.pr = pr; this.pn = pn; this.mY = mY; this.price = price; } // GETTER methods for accessing private data public double getPrice() { return price; } public String getProductName() { return productName; } public int getMfgYear() { return mfgYear; } public int getProductRating() { return productRating; } } // Class to compare Products by ratings class ProductRatingCompare implements Comparator<Product> { public int compare(Product m1, Product M2) { if (m1.getProductRating() < m2.getProductRating()) return -1; if (m1.getProductRating() > m2.getProductRating()) return 1; else return 0; } } // Class to compare Products by product name class ProductNameCompare implements Comparator<Product> { public int compare(Product m1, Product m2) { return m1.getProductName().compareTo(m2.getProductName()); } } |
|