

class Outer
{
class Inner { ... }
void someMethod()
{
Inner fred = new Inner();
...
}
}
class Outer
{
void someMethod()
{
class Inner { ... }
Inner fred = new Inner();
...
}
}
Arrays.sortComparator insteadComparator
public static void main(String[] args)
{
String[] names = { "Fred", "Wilma", "Barney" };
class LengthComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
return ((String) o1).length() - ((String) o2).length();
}
}
Arrays.sort(names, new LengthComparator());
}
Arrays.sort(names, new LengthComparator());
Comparator fred = new LengthComparator(); Arrays.sort(names, fred);
Arrays.sort(names, new Comparator()
{
public int compare(Object o1, Object o2)
{
return ((String) o1).length() - ((String) o2).length();
}
});
Let's make Item an inner class of
ArrayListAddressBook (from the lab):
public class ArrayListAddressBook
{
private class Item
{
String name;
String key;
String value;
}
...
}
Which of the following is true?
ArrayListAddressBook class can
construct and access Item objectsArrayListAddressBook class refers to
the inner class as ArrayListAddressBook.ItemItem class is poorly designed because the instance
variables of Item should have been declared as
privateItem class should have been added to the
AddressBook interface instead of
the ArrayListAddressBook classAddressBookpublic class MockAddressBook implements AddressBook
{
public void load(String sourceName) {}
public void save() {}
public void get(String name, String key) { return "Fred"; }
public void put(String name, String key, String value) {}
public void remove(String name, String key) {}
}
AddressBook book = new MockAddressBook()
to
AddressBook book = new ArrayListAddressBook()
Why is it necessary that the real class and the mock address book class implement the same interface?
Arrays and Collections
Platform interface provides services for getting data from
the web, storing/loading data on the device, running tasks in parallel,
etc.AndroidPlatform,
BlackberryPlatform, DesktopPlatformpublic void process(Sequence seq, int valuesToProcess)
{
for (int i = 1; i <= valuesToProcess; i++)
{
counters[seq.next() % 10]++;
}
}
public class SquareSequence implements Sequence
{
private int n;
public int next() { n++; return n * n; }
}
public class Mystery implements Sequence
{
private Sequence sequence;
public Mystery(Sequence sequence) { this.sequence = sequence; }
public int next() { return sequence.next() % 10; }
}
Which of the following is true?
Mystery object and calls next on
it, then an infinite recursion occurs, i.e. the next method
keeps calling itselfprocess method can be rewritten as
public void process(Sequence seq, int valuesToProcess)
{
Sequence digits = new Mystery(seq);
for (int i = 1; i <= valuesToProcess; i++) { counters[digits.next()]++; }
}
Sequence seq = new Mystery(new SquareSequence()); for (int i = 1; i <= 5; i++) System.out.print(seq.next());
prints 1491625
