12.6 Exercises
Factual
What methods are required for a class that is Iterable?
Which of the following is true about the
java.util.Set and thejava.util.Listinterfaces?Suppose we have a class that implements
Iterator. What methods must it override in order to compile?
Problem 2
If we add
String[][]objects to aSetand aList, the size of the set will always be less than or equal to the size of the list. Sets only have unique items, while lists can have duplicates, so if we add the same elements to both the list will always have at least as many elements as the set.The
java.util.ArrayListclass is an implementation of thejava.util.Listinterface. One implementation of theListinterface in Java is the ArrayList class.The
SetandListinterfaces extend theIterableinterface. Sets and Lists in Java can be used in enhanced for loops, which means that they areIterable.
Problem 3
An Iterator must override hasNext(), which returns a boolean indicating whether there are more elements in the Iterator, and next(), which returns the next item.
Conceptual
Why do we want to override the
.equalsmethod?
Problem 1
The .equals() method inherited from Object only checks if two items have the same memory address. This is undesireable behavior for many user-written classes in Java.
Metacognitive
In lecture, you built the
ArraySetIteratorclass. Modify the lecture class to take in aComparator<T>and an item of generic typeTcalledrefin the constructor. This new iterator should only return items greater thanT. For reference, the code forArraySetIteratoris included below.
Problem 7 from the Spring 2018 Midterm 2
Problem 2
Solutions and walkthrough are linked here and on the course website.