Java Notes
Comparator and Comparable
Comparable Interface:
Comparable is an interface in Java used to define the natural ordering of objects. It belongs to the
[Link] package and contains the method compareTo(). A class implements Comparable when it
wants its objects to be sorted in a default way. Example: Students can be sorted by roll number.
Comparator Interface:
Comparator is an interface in Java used to define custom sorting orders. It belongs to the [Link]
package and contains the method compare(). A separate Comparator class can be created to sort
objects in different ways. Example: Students can be sorted by name, marks, or age.
Difference:
1. Comparable provides natural sorting; Comparator provides custom sorting.
2. Comparable uses compareTo(); Comparator uses compare().
3. Comparable is in [Link]; Comparator is in [Link].
4. Comparable allows only one sorting order; Comparator allows multiple sorting orders.
Iterator and Iterable
Iterable Interface:
Iterable is an interface that represents a collection of elements that can be traversed. It contains the
iterator() method which returns an Iterator object. All collection classes such as ArrayList and
HashSet implement Iterable.
Iterator Interface:
Iterator is used to access elements of a collection one by one. It provides methods such as
hasNext(), next(), and remove(). Iterator allows safe traversal of collection elements without
exposing the internal structure.
Methods of Iterator:
1. hasNext() - Returns true if another element exists.
2. next() - Returns the next element in the collection.
3. remove() - Removes the current element from the collection.
Relationship:
Iterable provides the iterator() method, and Iterator performs the actual traversal of elements.