Difference between Comparator and Comparable in Java is very popular Java interview question mostly asked in telephonic round and writing code to sort object using Comparable or Comparator is popular on written test round of interview.The question was this “How you will sort Employee object based on his EmployeeID and his name” and this involves the use of both Comparable as well as Comparator interface in Java. This post is my revision on Java fundamentals similar to I did about equals method in Java and some tips to override hashCode in Java. All of these methods are fundamentals in Java programming language and correct understanding is must for any Java developer. Comparators and comparable in Java are two interfaces which is used to implement sorting in Java. It’s often required to sort objects stored in any collection classes like ArrayList, HashSet or in Array and that time we need to use either compare() or compareTo()method defined in java.util.Comparator and java.lang.Comparable. In this Java tutorial we will see example of Comparator and Comparable to sort object in Java and discuss some best practices around when to use Comparator interface etc. Any way before moving ahead Let’s see some important differences between Comparable and Comparator in Java.
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements