BAEL-6142 Map clear methods in Java (#14255)

Co-authored-by: Mariam Momjyan <mmomjyan@vmware.com>
This commit is contained in:
mmomjya 2023-09-11 18:40:30 +04:00 committed by GitHub
parent d2a1340d5c
commit 3d522eb8c4
2 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,49 @@
package com.baeldung.map;
import java.util.HashMap;
import java.util.Map;
public class MapClear {
public static Map returnCopyAndClearMap() {
// Create a HashMap
Map<String, Integer> scores = new HashMap<>();
Map<String, Integer> scores_copy;
// Add some key-value pairs
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
scores_copy = scores;
System.out.println("Before clearing: " + scores);
// Clear the map
scores.clear();
System.out.println("After clearing: " + scores);
return scores_copy;
}
public static Map returnCopyAndRewriteMap() {
// Create a HashMap
Map<String, Integer> scores = new HashMap<>();
Map<String, Integer> scores_copy;
// Add some key-value pairs
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 95);
scores_copy = scores;
System.out.println("Before clearing: " + scores);
// Create a new map
scores = new HashMap<>();
System.out.println("After clearing: " + scores);
return scores_copy;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.map;
import java.util.Map;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class MapClearUnitTest {
@Test
public void givenMap_returnEntryAndClearContent() {
Map entry = MapClear.returnCopyAndClearMap();
assertTrue(entry.isEmpty());
}
@Test public void givenMap_returnEntryAndRewriteContent() {
Map entry = MapClear.returnCopyAndRewriteMap();
assertTrue(!entry.isEmpty());
}
}