Menu

[Solved]1 Contact Task 15pts Public Class Contact Implements Comparable Class Maintains Informatio Q37282832

1. Contact Task:

(15pts) public class Contact implementsComparable<Contact> : This class maintains information for asingle contact, namely the following 3 instance variables aredefined: name, phone and email, all of type String.  Notethat this class will be used when defining an entry type for thehash map used in the PhoneBook class.  Furthermore, thisclass implements Comparable which makes instances of this class tobe comparable against others.  This is useful when weneed to call any of the generic methods in the Collection frameworkwhich requires a type that is comparable, such as the static methodCollections.sort defined in the Collections utilityclass.  Additionally, this class will provide thefollowing public methods:

  • A single parameterized constructor which receive 3 Stringparameters and use those values to initialize the 3 instancevariables defined by the class.
  • Accessor methods (get/set) for the instance variables asfollows: getName, getEmail, getPhone, setEmail, and setPhone. Onlya get method is needed for the name field (names cannot be changedafter a contact is created), while both set and get methods areexpected for both phone and email.
  • @Override public String toString() : returns a string in theformat “NAME, email: EMAIL, phone:PHONE.”. Note the dot “.” At the end of the line, forexample:

> Contact c = new Contact(“ArthurModdy”, “est@temp.com”, “703-555-5555”);

> System.out.println(c);

Arthur Moddy, email: est@temp.com,phone: 703-555-5555.

  • @Override public int compareTo(Contact c) This method willreturn the result of the comparing the lowercase versions of thename portions of both contacts (a String itself is also aComparable). More precisely, the method will convert the name ofthis contact and the name of c’s contact to lowercase and invokethe compareTo() method on the former, passing in the latter as anargument to the call. It will return an integer value which is theresult of the two name strings comparison.

2. PhoneBookUtils Task:

(30pts) public final class PhoneBookUtils : this is autility class, which means that we do not intend to instantiate itat all. Instead, we will use the static helper methods it provideswhile writing other classes. Examples of other utility classes arejava.lang.Math, java.util.Arrays, or even the class we wrote in thefirst project. Utility classes such as this one are often declaredfinal such that they cannot be subclassed.  We will useit to define generic methods with the idea that we could reuse thesame methods across a number of different applications.

In our phone book application, the utility class implements thefollowing static methods:

  • public static <KeyType, ValueType> String mapToString(Map<KeyType, ValueType> map): a generic method which receives aMap and returns a string containing all of the the map’s “entries.”It should use the toString() method of each map entry, and place anewline after each entry so that there is one entry per line.
  • public static <T extends Comparable<T>> StringlistToSortedList(List <T> list) : a generic method whichreceives a List and returns a string containing the “entries” inthe list in sorted order, separated by newlines so thatthere is one entry per line. The toString()method of each entryshould be used to obtain a string representation. A side effect ofthe method is that the input list should become sorted. This methodmay make use of the static helper method Collections.sort.
  • public static <T extends Comparable<T>> voidinsertionSort(T [] arr, int i) : a generic method which receives anarray and sorts the array elements using the insertion sortalgorithm. To sort the array, the method should intially be calledwith an i parameter of 0 or 1.   This method must berecursive as follows: when it is called, it should beassumed that the first i elements of the array are already sorted,while the remaining elements may or may not be. The sorted portionof the array will always have at least one element, because any oneelement is always in sorted order in relation to itself. Therecursive step will always place one additional element into sortedorder by inserting it into the sorted section, in its proper sortedposition, thus increasing the size of the sorted section by oneelement. Then, it will make a recursive call to sort the remainingelements.     In otherwords, the recursivestep works by assuming that subset arr[0..i-1] of the array isalready sorted, and works on the arr[i..n] (which is the unsortedsubset) by inserting first unsorted element (which is a[i]) intothe sorted region and incrementing the value of i for eachrecursive call.  The base case is reached once allelements have been placed into sorted order and there is nounsorted portion of the list remaining.
  • public static <T extends Comparable<T>> TbinarySearch(T arr[], int begin, int end, T key) : this genericmethod accepts an array and a key object returns the objectcontained in the array which matches the search key (usingcompareTo()) if found in the index range ≥ begin and < end, ornull if key is not found in that index range. You may assumethat the input array is already in sortedorder.  You may not call built-ins such asArrays.binarySearch() or Collections.binarySearch() as a part ofyour solution, and you must implement the binary search algorithmrecursively.

3. PhoneBook Task:

(40pts) public class PhoneBook implementsIterable<Contact> : Our phonebook class stores a list ofcontacts using a private HashMap data structure. As discussed inthe Overview section, the hashmap would hold values(“entries”) which are Contact objects, referenced by keys which arethe lowercase version of the contact’s name.   Thisclass provides the required functionality for maintaining the listof contacts: adding a new contact, updating a contact information,removing a contact, generating a list of all contacts, and sortingcontacts by last name.    This class can alsoread a list of contacts from an input file and can create aniterator to the list to be used when traversing the contactlist.  The PhoneBook class makes use of the availablestatic methods which are available in the PhoneBookUtils class. Allmethods which search for a contact by name (including all gettersand setters) should be case insensitive, meaning that the methodshould first convert the name parameter to lowercase beforesearching for it in the hashmap. This class will have the followingpublic methods:

  • A default constructor.
  • public boolean fileToMap(String filename): reads contactinformation from an input file into the hashmap.  Returns true if the file was successfully read orfalse otherwise.  The method should not throw anyexceptions and must handle the possible exception (for example ifthe file cannot be opened). Entries come in groups of three lines:first a name, then an email address, then a phone number. There areno blank lines between entries (you do not need to check for thisor to worry about whether the lines contain properly formatedemails or phones). If there are not enough lines in the file for afinal entry, then ignore the final one (but still returntrue). Here is an example of how data fields would appear inan input file (first-name last-name on one line, email on secondline, and phone on the third file):

    Lance Farmer

    sem.egestas@urnanecluctus.ca

    1-425-180-9073

    Lawrence Garcia

    diam@amagna.ca

    1-665-672-6398

    Petra Williamson

    euismod.in@convallisligulaDonec.co.uk

    1-352-344-9237

    Tip: names contain spaces, so you will most likely want to readby line rather than by token; check the available methods inScanner.

  • public boolean addContact(String name, String email, Stringphone): a Contact entry is created (refer to Contactclassdescription in this document) and stored as an entry value in theHashMap, using the an all-lowercase version of the contact’s nameas the key value (for example, the contact “George Mason” would usethe key “george mason”).  Since duplicates are notallowed, this method returns false whenever a key matching the samename (all lower case) exists in the map, true otherwise.
  • public boolean deleteContact(String name): removes the elementwith a matching key from the map, returns true if the contact isdeleted or false if the contact was not found in the map.
  • public Contact getContact(String name) a getter method whichfinds the contact with the matching key and returns the Contactwhich was found, or null if not found.
  • public String getContactInfo(String name) a getter method whichfinds the contact with the matching key and returns a textdescription of the contact using the toString() in Contact, or nullif not found.
  • public String getEmail(String name) and public StringgetPhone(String name), getter methods which find the contact withthe matching key and return a text description of the name/email ofthe contact, or null if not found. For either method, the methodshould return the description in the followingformat:”NAME: EMAIL” or “NAME:PHONE” .
  • For updating a contact, we define public booleanupdateEmail(String name, String email) and public booleanupdatePhone(String name, String phone) :  given a nameand an updated field, these methods will find the contact entry andupdate the given field (email / phone).  These methodsreturn true if an update is successful, or false if no matchingentry is found in the map.
  • public String getContactList()uses the helper static methodPhoneBookUtils.mapToString method to get a string representation ofthe hash map, and returns it.
  • public String getSortedContactList() which first converts thehash map “entries” into a List (for example type ArrayList) andthen invokes the helper static methodPhoneBookUtils.listToSortedList to get a string representation of asorted entry list, and returns it. This method should notchange the actual order of the entries within the hash map, hencethe intermediate step.  Hint: applying the.values() method on the hashmap will return a list of thehashmap entry values.
  • public String getSortedContactListAlt()this method firstconverts the hash map “entries” into an array of type Contact [](using the toArray(T[] a) method provided by the collection), thenit invokes the helper method PhoneBookUtils.insertionSort to getthe array sorted, and finally it returns a string representation ofthe sorted array.  The result of this method is identicalto the getSortedContactList(), but differs by implementing adifferent technique to sort.
  • public String searchContactList(String name): this method willreturn a string representation of the chosen contact, which is tobe found using the PhoneBookUtils.BinarySearch helper method. Asuggested approach is to first convert the hash map “entries” intoan array, then search for the contact within the array, finallyturning it into a string and returning the result. Note that evenif we do not know the email or phone, we can still use the searchby creating a dummy object with a blank email and phone. We wouldcreate a dummy object with the name of the person we are lookingfor and “” for email and phone, and search for the dummy in thelist. Since only the name field is used by the compareTo method inContact, the dummy object will succeed in finding the realcontact.   searchContactList returns a stringrepresentation of the contact object if it is found or nullotherwise.
  • @Override public Iterator<Contact> iterator()this methodwill return an iterator which will allow iterating over thecontacts in sorted order. A suggested approach is to first convertthe contact list hash map into an ArrayList of “entry” values, thensort the list using the static method Collections.sort, and finallyinstantiate a new iterator object by passing it the sorted arraylist. The method will return the created iterator object, whichiterates over the sorted “entry” values.

4. PhoneBookIterator Task:

(15pts) public class PhoneBookIterator<E>implements Iterator<E> :  An iteratorimplementation in Java is just a class which implementsthe Iteratorinterface.  Since we are going to use this class inside aPhoneBook we make this class an inner class (or nestedclass), which just means that we define it inside of thePhoneBook class.  We may make inner classes public orprivate, but for this project we will use public so that we can seethe implementation.

This iterator class will maintain two instance variables: aprivate ArrayList structure (which becomes the iterable object oncethe iterator is instantiated), and a private integer variable whichkeeps track of the current position of the iterator.  Itincludes the following public methods:

  • A single parameterized constructor which receives anArrayList<E> through its parameter list and uses it toinitialize its internal array list structure.  Theconstructor method would also initialize the position variable to0.
  • @Override public boolean hasNext(): returns true if there aremore objects in the iterable structure, or false otherwise.
  • @Override public E next(): returns the next element to be readfrom the iterable structure, and increases position forward by1.   This method must throw anNoSuchElementException() exception when there is no next element tobe read (position of iterator is beyond the size of the arraylist).

Expert Answer


Answer to 1. Contact Task: (15pts) public class Contact implements Comparable : This class maintains information for a single cont… . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *