๐ย ๐ย ๐ฆย ๐ย ๐ย ๐ฆย ๐ธ ๐ณย ๐ธย ๐ย ๐ฅย ๐ย ๐ฅ
Image source: https://refactoring.guru/
Joe
I have a collection of elements I don't know muchย about; but I know that there should be a next "next element".
I want to modify a collection (e.g. remove an element) while iterating over it
Intent: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying implementation
Iterable<E>
Iterator<E> iterator()
<<interface>>
Iterator<E>
boolean hasNext()
E next()
void remove()
<<interface>>
returns new MyCollectionIterator<E>()
MyCollection<E>
Iterator<E> iterator()
MyCollectionIterator<E>
public class ToyStore {
Inventory inventory = new Inventory();
public void displayInventory(){
System.out.println("Why hello! May I interest you in...");
for(Toy t : inventory){
tryToSell(t);
}
}
public void addToy(Toy t){ inventory.add(t); }
public static void main(String[] args) {
ToyStore allNaturalToys = new ToyStore();
allNaturalToys.addToy(new Toy("blocks"));
allNaturalToys.addToy(new Toy("sticks"));
allNaturalToys.addToy(new Toy("rocks"));
allNaturalToys.addToy(new Toy("wool"));
allNaturalToys.unstock(new Toy("blocks"));
allNaturalToys.displayInventory();
allNaturalToys.analyzeShopping();
}
private void unstock(Toy toy) { inventory.moveToBacklog(toy); }
private void analyzeShopping() { inventory.printQueryStats(); }
private void tryToSell(Toy t){ System.out.println("lovely "+t+"?"); }
}
public class Inventory {
private Collection<Toy> toys = new ArrayList<>();
private Collection<Toy> backlog = new ArrayList<>();
private ArrayList<String> log = new ArrayList<>();
// getters
public int getSize() { return toys.size(); }
public void add(Toy t) {
toys.add(t);
log.add("New toy added: "+t);
}
public void remove(Toy t){
toys.remove(t);
log.add("Toy "+t+" removed");
}
public void printQueryStats(){
for(String logEntry : log){
System.out.println(logEntry);
}
}
public void moveToBacklog(Toy toy) {
toys.remove(toy);
backlog.add(toy);
}
}
Part 1 - Consider the Inventory class from the Toy system in the Advanced Iterator videos. If we wanted to change the order in which the toys were returned such that it interleaved sale items and regular items, which parts of the Inventory class (and its associated Iterator inner class) would have to change?
Part 2ย - If you wanted to change the Inventory's iterator so that it iterates over objects of type String instead of Toy, what would need to change?
for (Long l : odds) {
assertTrue(l % 2 == 1);
if (l >= LIMIT) break;
}
AND THE WHOLE CLASS!
๐ญ๐ญ๐ฅน
Recommended Additional Reading:
https://refactoring.guru/design-patterns/iterator
And CPSC 213, and CPSC 221, and CPSC 310!
And the rest of computing!