I have the following Hashmap:
Map<String,String> studentGrades = new HashMap<>();
studentGrades.put("Tom", "A+");
studentGrades.put("Jack", "B+");
Iterator<Map.Entry<String,String>> iterator = studentGrades.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> studentEntry = iterator.next();
System.out.println(studentEntry.getKey() + " :: " + studentEntry.getValue());
iterator.remove();
}
I thought the iterator.remove();
meant that something would be removed from the HashMap
, for example iterator.remove("Tom");
, then when the iteration happens this is removed from the HashMap.
The program compiles and runs correctly when there iterator.remove();
but when it is iterator.remove("Tom");
an error is found. The compiler says
required: no arguments and found: java.lang.String reason: actual and formal arguments list differ in length.
Any reason why this is happening or have I got iterator.remove();
completely wrong?
Per the JavaSE 7 JavaDoc, the remove method for Iterator:
It removes the current element from the collection and "can be called only once per call to next()". It runs against the current value from the iteration and takes no arguments. It's also optional and I'm not certain what all you'd gain by your example. You should be fine without it.
As an aside: I would recommend, as you're iterating a HashMap that perhaps you try the for-in approach, as such:
UPDATE (per comment thread): As an aside, I gave this a go and it worked correctly, outputting without error. If you're dead set on using a java.util.Iterator with the Iterator's next remove method, this should work. I tested it in a scrapbook page for convenience.