I have the following:
fruitMap.remove(fruitId, fruitProperties);
The fruitMap is:
private Map<FruitId, FruitProperties> fruitMap = new HashMap<FruitId, FruitProperties>();
When I attempt to build my code I get a:
ERROR
The method remove(Object) in the type Map<MyImplementation.FruitId, FruitProperties>
is not applicable for the arguments (Map<MyImplementation.FruitId, FruitProperties>)
What is the issue?
Note that thiis call is inside of a method "removeFruit()" inside my "FruitImplementation" class.
From the Javadocs:
The default implementation is equivalent to, for this map:
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;
The default implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.
So you could use that default implementation. Put it in a static helper method maybe.
But if this is supposed to be thread-safe, you may need to add some synchronization code (or consider using a ConcurrentMap, which by the way already has the remove method since Java 5).
The remove(key, value)
method removes the entry for key
if it is currently mapped to value
. The method was added in Java 1.8. The Javadoc for the Map
interface mentions the following default implementation:
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.put(key, newValue);
return true;
} else
return false;
Since the Objects
class was only added in Java 1.7, for Java 1.6 you have to write the equality test yourself. So, if you don't need the return value of the method, you can replace map.remove(key, value)
with:
if (map.containsKey(key) {
Object storedValue = map.get(key);
if (storedValue == null ? value == null : storedValue.equals(value)) {
map.remove(key);
}
}
Note that this is not thread-safe. If you access the map from multiple threads, you will have to add a synchronized block.
You'll have to test the value yourself:
if(fruitProperties.equals(fruitMap.get(fruitId)) {
fruitMap.remove(fruitId);
}
Note, my implementation here assumes you are testing a non-null fruitProperties
object.
You need to do the following assuming your values cannot be null
if (fruitProperties.equals(fruitMap.get(fruitId))
fruitMap.remove(fruitId);
Note: for this to be thread safe you would need to wrap this in a synchronized
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With