实体类
public class User {
private String uid;
private String name;
private Set<String> phones;
public User() {
}
public User(String uid, String name, Set<String> phones) {
this.uid = uid;
this.name = name;
this.phones = phones;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getPhones() {
return phones;
}
public void setPhones(Set<String> phones) {
this.phones = phones;
}
@Override
public String toString() {
return "User{" +
"uid='" + uid + '\'' +
", name='" + name + '\'' +
", phones=" + phones +
'}';
}
}
测试类
public class TestA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("---------欢迎使用xxx通话录------------");
Map<String,User> map = new HashMap<>(); //创建map对象
while (true) {
System.out.println("1.录入信息");
System.out.println("2.查询指定信息");
System.out.println("3.查询所有信息");
System.out.println("4.删除信息");
int i = sc.nextInt();
if (i==1){
User user = new User();
System.out.println("请输入姓名:");
String name = sc.next();
while (true) {
System.out.println("请输入手机号1:");
String phone1 = sc.next();
System.out.println("请输入手机号2:");
String phone2 = sc.next();
Set<String> phones = new HashSet<>();
phones.add(phone1); //将手机号1添加到集合中
phones.add(phone2);
if (phones.size()==2){ //通过set集合判断用户输入的是否有重复的电话号码
user.setPhones(phones); //把用户设置到user对象中
break;
}else {
System.out.println("电话号码重复,请重新输入");
}
}
user.setName(name); //把姓名设置到用户中
user.setUid(System.currentTimeMillis()+""); //将产生随机的id设置到用户中
map.put(name,user); //将用户姓名和用户中的name和user添加到map集合中
}else if (i==2){
System.out.println("请输入用户名:");
String name2 = sc.next();
User user1 = map.get(name2); //通过map获得用户输入的信息,然后赋值给用户
if (user1==null){ //判断用户是否为空
System.out.println("查无此人!");
}else {
System.out.println(user1); //不为空就直接返回用户信息
}
}else if (i==3){
Set<String> st = map.keySet(); //通过map的键进行遍历
for (String s : st) {
System.out.println(s+map.get(s));
}
}else if (i==4){
System.out.println("请输入删除用户名:");
String name4 = sc.next();
User remove = map.remove(name4); //通过map删除出指定的输入信息,然后赋值给用户
if (remove==null){ //判断用户是否为空
System.out.println("查无此人,删除失败!");
}else {
System.out.println("删除成功!");
}
}else {
System.out.println("请输入正确编号");
}
}
}
}