From 8a31837a3e9006aa2aea36f64a5bed17fe61e33e Mon Sep 17 00:00:00 2001 From: mcasari Date: Tue, 14 Nov 2023 23:22:44 +0100 Subject: [PATCH] BAEL-6600: fix flaws in the logic of put method --- .../com/baeldung/map/HashMapWithMaxSizeLimit.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/HashMapWithMaxSizeLimit.java b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/HashMapWithMaxSizeLimit.java index 11845e6aa0..79c08dcb7c 100644 --- a/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/HashMapWithMaxSizeLimit.java +++ b/core-java-modules/core-java-collections-maps-7/src/main/java/com/baeldung/map/HashMapWithMaxSizeLimit.java @@ -11,17 +11,14 @@ public class HashMapWithMaxSizeLimit extends HashMap { public HashMapWithMaxSizeLimit(int maxSize) { super(); this.maxSize = maxSize; - } + } @Override public V put(K key, V value) { - V res = null; - if (this.maxSize == -1 || this.size() < this.maxSize) { - res = super.put(key, value); - } else if (this.maxSize != -1) { - throw new RuntimeException("Max size exceeded!"); - } - return res; + if (this.maxSize == -1 || this.containsKey(key) || this.size() < this.maxSize) { + return super.put(key, value); + } + throw new RuntimeException("Max size exceeded!"); } }