62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.Serializable;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Person implements Comparable<Person>, Serializable {
//构造函数
public Person(String firsName, String surname) {
this.firstName = firsName;
this.surname = surname;
}
public String toString() {
return firstName + " " + surname;
}
public int compareTo(Person person) {
int result =surname.compareTo(person.surname);
return result==0?firstName.compareTo(((Person)person).firstName):result;
}
//比较方法
public boolean equals(Object person) {
return compareTo((Person)person) == 0;
}
//生成散列码
public int hashCode() {
return 7*(firstName.hashCode())+13*(surname.hashCode());
}
//从键盘读取人的信息
public static Person readPerson() {
String firstName =null;
String surname = null;
try {
System.out.print("输入你的名字:");
firstName = keyboard.readLine().trim();
System.out.print("输入你的姓氏:");
surname = keyboard.readLine().trim();
} catch(IOException e) {
System.err.println("姓名输入错误!");
e.printStackTrace();
System.exit(1);
}
return new Person(firstName,surname);
}
private static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
private String firstName;
private String surname;
}