I'm trying to build an address book application, but before I start I'm familliaring my self with arrayLists of objects.
I have two classes (and a third tester class):
DirectoryEntry
PhoneDirectory
DirectoryEntry has a constructor that takes in two strings as arguments and saves then in class variables, name and number.
(for now) all PhoneDirectory does is ceate an arraylist:
dir = new ArrayList<DirectoryEntry>
and has a method to add an entry to the array list.
I want to us the indexOf("Stephen") to return an index number in the array, right now all I'm getting is -1.
What bugs me is that if I put something like:
DirectoryEntry name = dir.get(1);
I get the name and number in slot 4. I'm just not understanding the indexOf() and OOP : S please any help would be most welcome
public class Driver { public static void main(String[] args) { PhoneDirectory phone = new PhoneDirectory(); phone.addEntry("Stephen", "447-8067"); phone.addEntry("Vickie", "415-8006"); phone.addEntry("Jake", "675-8064"); phone.addEntry("Jen", "879-5684"); phone.addEntry("Anna", "710-4564"); phone.displayContents(); } }
import java.util.ArrayList; public class PhoneDirectory { public ArrayList<DirectoryEntry> dir; public PhoneDirectory() { dir = new ArrayList<DirectoryEntry>(); } public void addEntry(String name, String number) { dir.add(new DirectoryEntry(name,number)); } public void displayContents() { // DirectoryEntry aName = dir.get(3); int ind = dir.indexOf("Stephen"); System.out.println(ind); } }
public class DirectoryEntry { private String name; private String number; public DirectoryEntry(String name, String number) { this.name = name; this.number = number; } public String name() { return name; } @Override public String toString() { return name + " " + number; } }