【发布时间】:2018-03-21 20:29:40
【问题描述】:
我其实不知道问题出在哪里,所以我根据我的命名 自己的直觉。 这个简单的程序旨在演示静态变量和方法以及 hashMap 演示。
检索到的重复值是无法处理的,为什么 HashMap 中有重复值? 每次添加后不应该通过静态 hashMap 迭代识别可能的先前重复项并在功能上删除它们吗?
然后我尝试调用removeDups方法手动删除它们,这个尝试也失败了。
代码:
public class Registration {
public String name;
public static int count;
public static HashMap<Integer, Registration> listOfUsers = new HashMap<>();
public static ArrayList finalList = new ArrayList<>();
public Registration() {
}
public Registration(String name) {
this.name = name;
count++;
}
public static int getRegistered() {
return count;
}
public void putUserInDB(String name) {
listOfUsers.put(count, new Registration(name));
removeDups();
printUsers();
}
private static void removeDups() {
for (Integer key1 : listOfUsers.keySet()) {
for (Integer key2 : listOfUsers.keySet()) {
if (!key1.toString().equals(key2.toString())) {
Registration x = listOfUsers.get(key1);
Registration y = listOfUsers.get(key2);
if (x == y) {
listOfUsers.remove(key2);
}
}
}
}
}
private void printUsers() {
for (HashMap.Entry<Integer, Registration> e : listOfUsers.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}
}
@Override
public String toString() {
return "Name: " + this.name;
}
public class Test {
public static void main(String[]args) {
Registration r = new Registration();
r.putUserInDB("Olga");
r.putUserInDB("Maria");
r.putUserInDB("Tatiana");
System.out.println("No of registrations: " + r.getRegistered());
System.out.println("__________________________________________");
r.putUserInDB("Anastasia");
r.putUserInDB("Aleksandra");
System.out.println("No of registrations: " + r.getRegistered());
System.out.println("__________________________________________");
r.putUserInDB("Nikolai");
r.putUserInDB("Aleksei");
System.out.println("No of registrations: " + r.getRegistered());
}
输出:
0
姓名:奥尔加 0 姓名:奥尔加 1 姓名:玛丽亚 0 姓名:奥尔加 1 姓名:玛丽亚 2 姓名:塔蒂亚娜 注册数:3
【问题讨论】:
-
您没有重复。从构造函数调用
printUsers()时,您只是一遍又一遍地打印它。 -
地图有唯一的键,而在我看来你想要唯一的值......
-
不管怎样,你的钥匙是什么?静态场?你考虑过同步吗?为什么你甚至需要一张地图而不是一套,数量只是
set.size()...
标签: java static hashmap iterator