Comment on page
12.6 Exercises
- 1.What methods are required for a class that is Iterable?
- 2.Which of the following is true about the
java.util.Se
t and thejava.util.List
interfaces?- If we add
String[][]
objects to aSet
and aList
, the size of the set will always be less than or equal to the size of the list. - The
java.util.ArrayList
class is an implementation of thejava.util.List
interface. - The
Set
andList
interfaces extend theIterator
interface. - The
Set
andList
interfaces extend theIterable
interface.
- 3.Suppose we have a class that implements
Iterator
. What methods must it override in order to compile?
- If we add
String[][]
objects to aSet
and 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.ArrayList
class is an implementation of thejava.util.List
interface. One implementation of theList
interface in Java is the ArrayList class. - The
Set
andList
interfaces extend theIterable
interface. Sets and Lists in Java can be used in enhanced for loops, which means that they areIterable
.
- 1.Why do we want to override the
.equals
method?
- 1.In lecture, you built the
ArraySetIterator
class. Modify the lecture class to take in aComparator<T>
and an item of generic typeT
calledref
in the constructor. This new iterator should only return items greater thanT
. For reference, the code forArraySetIterator
is included below.
private class ArraySetIterator implements Iterator<T> {
private int pos;
public ArraySetIterator() {
pos = 0;
}
public boolean hasNext() {
return pos < size;
}
public T next() {
T returnItem = items[pos];
pos += 1;
return returnItem;
}
}
- 2.Problem 7 from the Spring 2018 Midterm 2
public class ArraySetGreaterIterator implements Iterator<T> {
private int pos;
private T ref;
private Comparator<T> comp;
public ArraySetGreaterIterator(T ref, Comparator<T> comp) {
this.ref = ref;
this.comp = comp;
}
@Override
public boolean hasNext() {
return pos < size;
}
@Override
public T next() {
T returnItem = items[pos];
while (comp.compare(returnItem, ref) <= 0) {
pos += 1;
returnItem = items[pos];
}
return returnItem;
}
}
Last modified 9mo ago