Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- **What is the difference between Comparator and Comparable**
- ___
- | Comparable interface | Comparator interface |
- | ------------ | ------------ |
- | Present in **java.lang package** |Present in **java.util package** |
- | Defines one important method i.e. <br> public int **compareTo**(Object obj); |Defines 2 method i.e.; <br>public int **compare**(Object obj1, Object obj2);<br> public boolean **equals**(Object object);|
- | It is basically used for default **natural sorting order** | This is preferred for **customized sorting order** |
- | This interface need to be implemented in the same class for which sorting is required | Separate class is required to implement Comparator interface |
- | Elements of List can be sorted using comparable interface using sort(); method of Collections class, as shown below<br>**Example**: Collection.sort(listItems); | Elements of List can be sorted using comparator interface using sort(); method of Collections class, as shown below<br>**Example**: Collection.sort(listItems, comparator);|
- | String & wrapper classes’ like Integer, Double, etc implement comparable interface | There are very few classes’ which implements Comparator interface|
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement