**Compare and Iterate**
*Thu Oct 15*
# Comparable Interface
As we've seen in class, if we want to sort a class of our own making, it is often useful to tell Java that our class is "comparable". We do this by implementing the `Comparable` interface.
This requires us to:
1. Implement `Comparable`
2. Implement a `compareTo(T that)` method
See [this `Comparable` lecture code example](https://github.com/pomonacs622020fa/LectureCode/blob/master/CompareAndIterate/StudentComp.java).
# Comparator Interface
Sometimes we want more flexibility in sorting than can be provided by the `Comparable` interface. For example, what if we want to sort by some instance variable other than what is defined in `compareTo`? We could extend `compareTo` and add a static variable that tells it what to use (like the quiz), but there is a better method: the `Comparator` interface.
This interface requires us to:
1. Implement `Comparator`
2. Implement an anonymous inner class.
See [this `Comparator` lecture code example](https://github.com/pomonacs622020fa/LectureCode/blob/master/CompareAndIterate/StudentComp.java).
# Iterator Interface
A few times in class, I have use the for-each loop:
~~~java linenumbers
for (String s : myStrings) {
System.out.println(s);
}
~~~
But how can we make our class take on the part of `myStrings` above? Java has a notion of iterators. To make our class work in this scenario, we just need to implement the `Iterable` interface.
This interface requires us to:
1. Implement `Iterable`
2. Make a private inner class that implements the `Iterator` interface
3. Override the `iterator()` method of our class
See [this `Iterable` lecture code example](https://github.com/pomonacs622020fa/LectureCode/blob/master/CompareAndIterate/StudentIter.java).
# Walk-Through
Here is a video walking through the code linked above: