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?
There are two methods named
removein different classes/interfaces.Iterator'sremove()removes the previous item returned.Collection'sremove(object)removes a specific object from a collectionOnly the second has a
objectparameter. But beware: using it invalidates iterators, so don't call it from a loop over the same collection, it will not work. For filtering, use an iterator (like you do), and itsremove()method.