Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
| Exercise 35 Walking a List. |
Consider the code used in Exercise 4 (Chapter 3).
▪ See Appendix A for solutions. |
| Exercise 36 Middle Man. (Challenging). |
Consider these classes:
(This code has been greatly simplified; the queue wasn't originally storing strings.) Queue.java
import java.util.ArrayList;
public class Queue {
ArrayList delegate = new ArrayList();
public Queue() {}
public void addRear(String s) {delegate.add(s);}
public int getSize() {return delegate.size();}
public String removeFront() {
String result = delegate.get(0).toString();
delegate.remove(0);
return result;
}
}
QueueTest.java (selection)
public void testQ() {
Queue q = new Queue();
q.addRear("E1");
q.addRear("E2");
assertEquals("E1", q.removeFront());
assertEquals("E2", q.removeFront());
assertEquals(0, q.getSize());
}
▪ See Appendix A for solutions. |
| Exercise 37 Cart. (Challenging). |
Consider these classes:
Here is Cart.cost():
public int cost() {
int total = 0;
for (int i=0; i < purchases.size(); i++) {
Purchase p = (Purchase) purchases.elementAt(i);
total += p.item().cost + p.shipping().cost;
}
return total;
}
▪ See Appendix A for solutions. |
| Exercise 38 Trees in Swing. (Challenging). |
In Swing, JTree is in the javax.swing package, and TreeModel and DefaultTreeModel are in the javax.swing.tree package. (The table classes have a similar organization.)
▪ See Appendix A for solutions. |