Reputation: 857
In all element in Entry Map, I only can remove the one element at least position. Can anybody explain what reason ?
Ps: I think problem at EntryMap with HashMap
This is full code:
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Neti {
static Map<Integer, String> mm = new HashMap<>();
static void removeEntry(Integer val) {
for (Entry<Integer, String> entry : mm.entrySet()) {
if (entry.getKey() == val) {
mm.remove(val);
break;
}
}
}
public static void main(String[] args) {
mm.put(123, "one");
mm.put(1234, "two");
mm.put(12345, "three");
mm.put(123456, "four");
Scanner scanner = new Scanner(System.in);
System.out.println("We have: " + mm);
for (;;) {
System.out.print("Number to remove: ");
int val = scanner.nextInt();
removeEntry(val);
System.out.println("Map entries are: " + mm.toString());
}
}
}
Upvotes: 2
Views: 137
Reputation: 393811
Your entire removeEntry
method can be replaced by a single statement - mm.remove(val)
. There's no need to iterate over the entrySet
to find the key you wish to remove, and even if there was, using ==
for reference types is usually wrong.
Upvotes: 3