ArrayLists and Iterators
29. Playful Program
Answer:
Of course. Playing with things always helps to understand them.
Playful Program
import java.util.* ; class Entry { private String name; private String number; // constructor public Entry( String n, String num ) { name = n; number = num; } // methods public String getName() { return name ; } public String getNumber() { return number ; } public boolean equals( Object other ) { System.out.print (" Compare " + other + " To " + this ); System.out.println(" Result: " + name.equals( ((Entry)other).name ) ); return getName().equals( ((Entry)other).getName() ); } public String toString() { return "Name: " + getName() + "; Number: " + getNumber() ; } } public class PhoneBookTest { public static void main ( String[] args) { ArrayList<Entry> phone = new ArrayList<Entry>(); phone.add( new Entry( "Amy", "123-4567") ); phone.add( new Entry( "Bob", "123-6780") ); phone.add( new Entry( "Hal", "789-1234") ); phone.add( new Entry( "Deb", "789-4457") ); phone.add( new Entry( "Zoe", "446-0210") ); // Look for Hal in phone. The indexOf() method uses the // equals(Object) method of each object in the list. // System.out.println("Begin Search" ); Entry target = new Entry( "Hal", null ); int spot = phone.indexOf( target ) ; System.out.println("End Search" ); System.out.println( "indexOf returns: " + spot ) ; } } |
Question 28:
Could the program be altered so that it searches for a name entered by the user?
(It would be good practice for you to do this before you go on.)