// Implements a sorted map with a linked list import java.util.*; import java.io.*; class Name implements Comparable { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public Name() {} public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getLastName() { return lastName; } public int compareTo(Name name) { int result = lastName.compareTo(name.getLastName()); if (result==0) result = firstName.compareTo(name.getFirstName()); return result; } } class DuplicateKey extends Exception { public DuplicateKey() { super("Duplicated name"); } } class NotFound extends Exception { public NotFound() { super("Name not found"); } } public class LinkedMap { private String filename; protected TreeMap treeMap = null; // Constructor public LinkedMap(String filename) { this.filename = filename; treeMap = new TreeMap (); try { FileReader file = new FileReader(filename); BufferedReader buffer = new BufferedReader(file); while (true) { String line = buffer.readLine(); if (line==null) break; if (line.length()==0) continue; Merchant merchant = new Merchant(); merchant.inputFile(line); treeMap.put(new Name(merchant.firstName, merchant.lastName), merchant); } buffer.close(); file.close(); } catch (Exception e) { System.out.println(e); } } // Inserts a key-value pair into the map public void insert(Merchant merchant) throws DuplicateKey { Name name = new Name(merchant.firstName, merchant.lastName); if (search(name)) throw new DuplicateKey(); treeMap.put(name, merchant); } // Removes a key-value pair from the map public void remove(Name name) throws NotFound { if (!search(name)) throw new NotFound(); treeMap.remove(name); } // Finds and returns a value given a key // Returns null if not found public Merchant find(Name name) { if (search(name)) return treeMap.get(name); else return null; } // Returns a string representation of the entire map public String toString() { Set set = treeMap.keySet(); Iterator it = set.iterator(); StringBuffer sb = new StringBuffer(); while (it.hasNext()) { Name name = it.next(); Merchant merchant = treeMap.get(name); sb.append(merchant.toString() + "\n"); } return sb.toString(); } // Searches for specified key; leaves position in previous and current private boolean search(Name name) { Merchant merchant = treeMap.get(name); if (merchant==null) return false; return true; } // Save to file public void save() { try { FileWriter file = new FileWriter(filename); PrintWriter pw = new PrintWriter(file); Set set = treeMap.keySet(); Iterator it = set.iterator(); while (it.hasNext()) { Name name = it.next(); Merchant merchant = treeMap.get(name); pw.println(merchant.toString()); } pw.close(); file.close(); } catch (Exception e) { System.out.println(e); } } }