//**************************************************************// //***************Iterators - November 2nd, 2016****************// //************************************************************// Prof. Simpkins is sick, so we get Taylor teaching today instead ---------------------------------------------------------------- -Comparable / Comparator: know that these are TWO DIFFERENT THINGS -Comparable is an interface that, when implemented, allows it to be compared to any other object that implements "Comparable" -Defines a default - or NATURAL - ordering -COMPARATOR is a tool to define a different way of sorting things (e.g., by 2 criteria) -All collections are, by default, ITERABLE; i.e., we can call a "for-each" loop on it -how does it know how to cycle through these collections? By how we implement the "Iterable" interface -Why is this necessary? Why can't we just go to the next one? Because Collections AREN'T NEXT TO EACH OTHER IN MEMORY; they're stored in separate data structures, so the compiler can't tell what order everything is in by itself -The Iterable interface has 1 sub-interface: "Iterator", which has 3 methods (2 that we care about): -"hasNext()"; tells us if there's still another element in the collection -"next()"; returns the next element -"remove()": default method as of Java 8, so we don't need to worry about this any more; removes the most recently returned element -ALWAYS call hasNext() before calling next() e.g. "while (Collector.hasNext()) { object x = Collector.next(); }" -Should usually have a counter variable for what the next element is in the backing structure; e.g. "public boolean hasNext() { return counter > 0; } public E next() { if(hasNext()) { E next = get(counter); counter--; return next; } }" -Not too hard conceptually, but if it is, it's VERY straightforward in practice