Comparables and Iterators
Notes from Josh Hug's lecture videos.
Iterators
Iterators are useful for data structures that store objects, as they allow users to go through them one by one. Syntax wise, if Steven
is a data structure, then we must do the following.
Steven<T>
implementsIterable<T>
. It implements its interface method,iterator();
, that returns aStevenIterator
.The
Steven
class should have aStevenIterator
subclass, that implementsIterable<T>
.StevenIterable
should implementIterable
's interface methods,T next();
andboolean hasNext();
.StevenInstance.iterator();
should returnnew StevenIterator();
.
Many Java built-in data structures, such as ArrayList
and LinkedList
, already implement Iterable<T>
, which is useful because you can get an Iterator
object from them whenever you want.
If an object implements Iterable
, you can use an enhanced for loop on it.
Comparables
A lot of data structures, such as BSTs, rely on objects being comparable. We can make any object we want comparable by doing the following.
The object should implement
Comparable
.The object should then implement its interface method,
int compareTo(T item);
. This method usually returns negative if the object invoking it is less than item, positive if vice versa, and zero if equal.
Last updated