控制台程序。

首先改进Peron类,使Person可以在地图中用作键,进而存储电话簿中的项。必须添加equals()方法并重写默认的hashCode()方法。

 import java.io.*;

 public class Person implements Comparable<Person>, Serializable {
// Constructor
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
} @Override
public String toString() {
return firstName + " " + surname;
} // Compare Person objects
public int compareTo(Person person) {
int result = surname.compareTo(person.surname);
return result == 0 ? firstName.compareTo(person.firstName) : result;
} @Override
public boolean equals(Object person) {
return compareTo((Person)person) == 0;
} @Override
public int hashCode() {
return 7*firstName.hashCode()+13*surname.hashCode();
} // Read a person from the keyboard
public static Person readPerson() {
String firstName = null;
String surname = null;
try {
System.out.print("Enter first name: ");
firstName = keyboard.readLine().trim();
System.out.print("Enter surname: ");
surname = keyboard.readLine().trim();
} catch(IOException e) {
System.err.println("Error reading a name.");
e.printStackTrace(System.err);
System.exit(1);
}
return new Person(firstName,surname);
} private String firstName; // First name of person
private String surname; // Second name of person
private static final long serialVersionUID = 1001L;
private static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
}

对于可在散列表中用作键的自定义类对象来说,必须重写Object类的equals()方法。该方法有HashMap<>类中的方法用于确定两个键何时相等。

还可以重写默认的hashCode()方法,将对象的散列值返回为int类型。这个hashCode()方法用于生成一个值,从而确定键/值位于什么地方。

 import java.io.*;

 class PhoneNumber implements Serializable {
public PhoneNumber(String areacode, String number) {
this.areacode = areacode;
this.number = number;
} @Override
public String toString() {
return areacode + " " + number;
} // Read a phone number from the keyboard
public static PhoneNumber readNumber() {
String area = null; // Stores the area code
String localcode = null; // Stores the local code
try {
System.out.print("Enter area code: ");
area = keyboard.readLine().trim();
System.out.print("Enter local code: ");
localcode = keyboard.readLine().trim();
System.out.print("Enter the number: ");
localcode += " " + keyboard.readLine().trim();
} catch(IOException e) {
System.err.println("Error reading a phone number.");
e.printStackTrace();
System.exit(1);
}
return new PhoneNumber(area,localcode);
} private String areacode;
private String number;
private static final long serialVersionUID = 1001L;
private static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
}
 import java.io.Serializable;

 class BookEntry implements Serializable {
public BookEntry(Person person, PhoneNumber number) {
this.person = person;
this.number = number;
} public Person getPerson() {
return person;
} public PhoneNumber getNumber() {
return number;
} @Override
public String toString() {
return person.toString() + '\n' + number.toString();
} // Read an entry from the keyboard
public static BookEntry readEntry() {
return new BookEntry(Person.readPerson(), PhoneNumber.readNumber());
} private Person person;
private PhoneNumber number;
private static final long serialVersionUID = 1001L;
}
 import java.io.Serializable;
import java.util.HashMap; class PhoneBook implements Serializable {
public void addEntry(BookEntry entry) {
phonebook.put(entry.getPerson(), entry);
} public BookEntry getEntry(Person key) {
return phonebook.get(key);
} public PhoneNumber getNumber(Person key) {
BookEntry entry = getEntry(key);
if(entry != null) {
return entry.getNumber();
} else {
return null;
}
} private HashMap<Person,BookEntry> phonebook = new HashMap<>();
private static final long serialVersionUID = 1001L;
}
 import java.io.StreamTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException; public class FormattedInput { public int readInt() throws InvalidUserInputException {
if (readToken() != StreamTokenizer.TT_NUMBER) {
throw new InvalidUserInputException("readInt() failed." + "Input data not numeric");
} if (tokenizer.nval > (double) Integer.MAX_VALUE || tokenizer.nval < (double) Integer.MIN_VALUE) {
throw new InvalidUserInputException("readInt() failed." + "Input outside range of type int");
} if (tokenizer.nval != (double) (int) tokenizer.nval) {
throw new InvalidUserInputException("readInt() failed." + "Input not an integer");
}
return (int) tokenizer.nval;
} public double readDouble() throws InvalidUserInputException {
if (readToken() != StreamTokenizer.TT_NUMBER) {
throw new InvalidUserInputException("readDouble() failed." + "Input data not numeric");
}
return tokenizer.nval;
} public String readString() throws InvalidUserInputException {
if (readToken() == StreamTokenizer.TT_WORD || ttype == '\"' || ttype == '\"') {
return tokenizer.sval;
} else {
throw new InvalidUserInputException("readString() failed." + "Input data is not a string");
}
}
// Plus methods to read various other data types... // Helper method to read the next token
private int readToken() {
try {
ttype = tokenizer.nextToken();
return ttype; } catch (IOException e) { // Error reading in nextToken()
e.printStackTrace();
System.exit(1); // End the program
}
return 0;
} // Object to tokenize input from the standard input stream
private StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
private int ttype; // Stores the token type code
}
 public class InvalidUserInputException extends Exception {
public InvalidUserInputException() { } public InvalidUserInputException(String message) {
super(message);
} private static final long serialVersionUID = 9876L; }
 public class TryPhoneBook {
public static void main(String[] args) {
PhoneBook book = new PhoneBook(); // The phone book
FormattedInput in = new FormattedInput(); // Keyboard input
Person someone;
while(true) {
System.out.println("Enter 1 to enter a new phone book entry\n"+
"Enter 2 to find the number for a name\n"+
"Enter 9 to quit.");
int what = 0; // Stores input selection
try {
what = in.readInt(); } catch(InvalidUserInputException e) {
System.out.println(e.getMessage()+"\nTry again.");
continue;
} switch(what) {
case 1:
book.addEntry(BookEntry.readEntry());
break;
case 2:
someone = Person.readPerson();
BookEntry entry = book.getEntry(someone);
if(entry == null) {
System.out.println("The number for " + someone + " was not found.");
} else {
System.out.println("The number for " + someone + " is " + entry.getNumber());
}
break;
case 9:
System.out.println("Ending program.");
return;
default:
System.out.println("Invalid selection, try again.");
break;
}
}
}
}

Java基础之集合框架——使用HashMap地图(TryPhoneBook1)的更多相关文章

  1. Java基础--说集合框架

    版权所有,转载注明出处. 1,Java中,集合是什么?为什么会出现? 根据数学的定义,集合是一个元素或多个元素的构成,即集合一个装有元素的容器. Java中已经有数组这一装有元素的容器,为什么还要新建 ...

  2. 黑马程序员——【Java基础】——集合框架

    ---------- android培训.java培训.期待与您交流! ---------- 一.集合框架概述 (一)集合框架中集合类关系简化图 (二)为什么出现集合类? 面向对象语言对事物的体现都是 ...

  3. Thinking in java基础之集合框架(转载)

    集合简介(容器)把具有相同性质的一类东西,汇聚成一个整体,就可以称为集合,例如这里有20个苹果,我们把每一个苹果当成一个东西(一个对象),然后我们借用袋子把这20个苹果装起来,而这个袋子就是集合(也叫 ...

  4. java基础之集合框架

    6.集合框架: (1)为什么出现集合类? 面向对象对事物的体现都是以对象的形式,为了方便对多个对象的操作,就对对象进行存储. 集合就是存储对象最常用的一种方式. (2)数组和集合都是容器,两者有何不同 ...

  5. java基础37 集合框架工具类Collections和数组操作工具类Arrays

    一.集合框架工具类:Collections 1.1.Collections类的特点 该工具类中所有的方法都是静态的 1.2.Collections类的常用方法 binarySearch(List< ...

  6. Java基础之集合框架(Collection接口和List接口)

    首先我们说说集合有什么作用. 一.集合的作用 1.在类的内部,对数据进行组织: 2.简单而快速的搜索大数量的条目: 3.有的集合接口,提供一系列排列有序的元素,并且可以在序列中间快速的插入或者删除有关 ...

  7. Java基础之集合框架——在文件中存储地图(TryPhoneBook2)

    控制台程序. import java.io.*; public class Person implements Comparable<Person>, Serializable { // ...

  8. Java基础之集合框架类及泛型简介

    Collection接口 Collection 通用的常见方法 add()添加一个元素,可以指定脚标 addAll()将一个collection放入 clear()清除 remove()删除元素,返回 ...

  9. Java基础之集合框架——使用堆栈Stack<>对象模拟发牌(TryDeal)

    控制台程序. public enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, A ...

随机推荐

  1. NSDate 获取明天、后天的日期

    NSDate *  senddate=[NSDate date];    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIde ...

  2. 估值十亿美元、1.5亿用户,公司CEO却跑路了

    转载这篇文章是觉得配图非常好玩的,文章的真实性有待证明 年收益3600万美元的.曾经拥有高口碑产品的Evernote,却正在把一手好牌打烂,距离IPO越来越远,屡屡被业界唱衰. "独角兽公司 ...

  3. javascript 原生事件综合查询

    click() 对象.click() 使对象被点击. closed 对象.closed 对象窗口是否已关闭true/false clearTimeout(对象) 清除已设置的setTimeout对象 ...

  4. mysql慢查询

    查看当前服务器是否开启慢查询: 1.快速办法,运行sql语句show VARIABLES like "%slow%" 2.直接去my.conf中查看. my.conf中的配置(放在 ...

  5. Linus:利用二级指针删除单向链表

    Linus大神在slashdot上回答一些编程爱好者的提问,其中一个人问他什么样的代码是他所喜好的,大婶表述了自己一些观点之后,举了一个指针的例子,解释了什么才是core low-level codi ...

  6. 在VC6.0中编译头文件时产生moc文件

    1.在FileView视图中 右键点击需要产生moc文件的头文件(就是类中包含Q_OBJECT宏,如果没有这个宏就不需要产生moc文件) 2.在右键菜单中选择Setting... 3.选择Custom ...

  7. 国家发改委发布的数据,前三季度我国生产的手机、PC、集成电路、宽带上网的数量

    集微网消息,根据国家发改委发布的数据,前三季度,我国生产集成电路944亿块,同比增长18.2%. 此外,前三季度,生产手机15亿部,同比增长17.6%,其中智能手机11亿部,增长12.1%,占全部手机 ...

  8. VS2013修改MVC4默认生成的模板

    找到以下目录,根据VS版本和安装目录不同相应改动: I:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTempla ...

  9. 让Dreamweaver支持less

    编辑->首选参数->文件类型/编辑器->在代码视图中打开->添加" .less"后缀

  10. yum安装node.js

    1.安装EPEL库 yum install epel-release 2.安装Node.js yum install nodejs 3.安装nodejs中常用的npm软件包管理器 yum instal ...