import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ExploreHashMap {
private static String escapeJson(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (c < 0x20) sb.append(String.format("\\u%04x", (int) c));
else sb.append(c);
}
}
return sb.append('"').toString();
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
if (obj instanceof String) return escapeJson((String) obj);
if (obj instanceof List<?>) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(toJson(list.get(i)));
}
return sb.append("]").toString();
}
if (obj instanceof Map<?, ?>) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
if (!first) sb.append(", ");
first = false;
sb.append(escapeJson(String.valueOf(e.getKey()))).append(": ").append(toJson(e.getValue()));
}
return sb.append("}").toString();
}
return escapeJson(String.valueOf(obj));
}
private static Map<String, Object> makeCase(String name, String summary, Object expected, Object actual) {
Map<String, Object> c = new LinkedHashMap<String, Object>();
c.put("name", name);
c.put("summary", summary);
c.put("expected", expected);
c.put("actual", actual);
c.put("passed", expected.equals(actual));
return c;
}
public static void main(String[] args) {
List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();
// Case 1: Integer/String & String/String CRUD, single null key, remove, clear, size
{
HashMap<Integer, String> sites = new HashMap<Integer, String>();
sites.put(1, "Google");
sites.put(2, "Atlas");
sites.put(3, "Taobao");
sites.put(4, "Zhihu");
boolean interfacesOk = (sites instanceof Map) && (sites instanceof Cloneable) && (sites instanceof Serializable);
String val3 = sites.get(3);
int size4 = sites.size();
HashMap<Integer, String> afterRemove = new HashMap<Integer, String>(sites);
String removed4 = afterRemove.remove(4);
HashMap<String, String> strMap = new HashMap<String, String>();
strMap.put("one", "Google");
strMap.put("two", "Atlas");
strMap.put(null, "first-null");
strMap.put(null, "overwritten-null");
HashMap<Integer, String> cleared = new HashMap<Integer, String>(sites);
cleared.clear();
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("implements_interfaces", true);
expected.put("get_key_3", "Taobao");
expected.put("initial_size", 4);
expected.put("removed_key_4", "Zhihu");
expected.put("size_after_remove", 3);
expected.put("null_key_overwritten", "overwritten-null");
expected.put("str_map_size", 3);
expected.put("empty_after_clear", true);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("implements_interfaces", interfacesOk);
actual.put("get_key_3", val3);
actual.put("initial_size", size4);
actual.put("removed_key_4", removed4);
actual.put("size_after_remove", afterRemove.size());
actual.put("null_key_overwritten", strMap.get(null));
actual.put("str_map_size", strMap.size());
actual.put("empty_after_clear", cleared.isEmpty());
cases.add(makeCase(
"hashmap_crud_and_null_key",
"验证 HashMap 泛型键值对增删查、单 null 键覆盖规则与 clear/isEmpty/size",
expected,
actual
));
}
// Case 2: Iteration via keySet, values, entrySet, forEach
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Google");
map.put(2, "Atlas");
map.put(3, "Taobao");
map.put(4, "Zhihu");
List<Integer> keys = new ArrayList<Integer>(map.keySet());
Collections.sort(keys);
List<String> byKeySet = new ArrayList<String>();
for (Integer k : keys) {
byKeySet.add(k + ":" + map.get(k));
}
List<String> vals = new ArrayList<String>(map.values());
Collections.sort(vals);
List<String> byEntry = new ArrayList<String>();
for (Map.Entry<Integer, String> e : map.entrySet()) {
byEntry.add(e.getKey() + ":" + e.getValue());
}
Collections.sort(byEntry);
List<String> byForEach = new ArrayList<String>();
map.forEach((k, v) -> byForEach.add(k + ":" + v));
Collections.sort(byForEach);
List<String> expPairs = Arrays.asList("1:Google", "2:Atlas", "3:Taobao", "4:Zhihu");
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("by_keyset", expPairs);
expected.put("sorted_values", Arrays.asList("Atlas", "Google", "Taobao", "Zhihu"));
expected.put("by_entryset", expPairs);
expected.put("by_foreach", expPairs);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("by_keyset", byKeySet);
actual.put("sorted_values", vals);
actual.put("by_entryset", byEntry);
actual.put("by_foreach", byForEach);
cases.add(makeCase(
"hashmap_iteration_views",
"验证 HashMap 的 keySet()、values()、entrySet() 与 Java 8 forEach() 遍历视图",
expected,
actual
));
}
// Case 3: Full Java 8 HashMap API (clone, putAll, putIfAbsent, containsKey, containsValue, replace, replaceAll, getOrDefault, merge, compute, computeIfAbsent, computeIfPresent)
{
HashMap<String, Integer> scores = new HashMap<String, Integer>();
scores.put("math", 80);
HashMap<String, Integer> extra = new HashMap<String, Integer>();
extra.put("eng", 90);
scores.putAll(extra);
Integer keptMath = scores.putIfAbsent("math", 99);
Integer addedArt = scores.putIfAbsent("art", 75);
boolean hasMath = scores.containsKey("math");
boolean has90 = scores.containsValue(90);
Integer fallback = scores.getOrDefault("phy", -1);
scores.replace("art", 85);
scores.merge("math", 5, Integer::sum);
scores.compute("eng", (k, v) -> v + 2);
scores.computeIfAbsent("bio", k -> 70);
scores.computeIfPresent("bio", (k, v) -> v + 10);
@SuppressWarnings("unchecked")
HashMap<String, Integer> cloned = (HashMap<String, Integer>) scores.clone();
cloned.replaceAll((k, v) -> v * 2);
Map<String, Object> expected = new LinkedHashMap<String, Object>();
expected.put("putIfAbsent_existing_returns_old", 80);
expected.put("putIfAbsent_new_returns_null", true);
expected.put("contains_key_and_val", Arrays.asList(true, true));
expected.put("get_or_default_missing", -1);
expected.put("scores_after_updates", Arrays.asList(85, 80, 92, 85));
expected.put("cloned_doubled_math", 170);
Map<String, Object> actual = new LinkedHashMap<String, Object>();
actual.put("putIfAbsent_existing_returns_old", keptMath);
actual.put("putIfAbsent_new_returns_null", addedArt == null);
actual.put("contains_key_and_val", Arrays.asList(hasMath, has90));
actual.put("get_or_default_missing", fallback);
actual.put("scores_after_updates", Arrays.asList(
scores.get("art"), scores.get("bio"), scores.get("eng"), scores.get("math")
));
actual.put("cloned_doubled_math", cloned.get("math"));
cases.add(makeCase(
"hashmap_java8_compute_merge_replace",
"验证 HashMap 全部核心与 Java 8 扩展方法(clone/putAll/putIfAbsent/contains/replace/replaceAll/getOrDefault/merge/compute 系列)",
expected,
actual
));
}
Map<String, Object> root = new LinkedHashMap<String, Object>();
root.put("version", "OpenJDK " + System.getProperty("java.version"));
root.put("cases", cases);
System.out.println(toJson(root));
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/java-hashmap-lab/ExploreHashMap.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreHashMap.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1121.zip