Testing code that utilizes HashMap in Java is essential to ensure the integrity and performance of the data structure. HashMap provides a way to store key-value pairs, allowing for efficient data retrieval. Below is a simple example of a HashMap implementation in Java, along with basic unit tests using JUnit.
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Test;
public class HashMapTest {
@Test
public void testHashMap() {
HashMap map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
// Test size
Assert.assertEquals(3, map.size());
// Test containsKey
Assert.assertTrue(map.containsKey("two"));
// Test get
Assert.assertEquals(Integer.valueOf(2), map.get("two"));
}
@Test
public void testRemove() {
HashMap map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.remove("one");
// Test removal
Assert.assertFalse(map.containsKey("one"));
Assert.assertEquals(1, map.size());
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?