import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
public class ExploreDataStructures {
static class CaseResult {
final String name;
final String summary;
final String expectedJson;
final String actualJson;
final boolean passed;
CaseResult(String name, String summary, String expectedJson, String actualJson) {
this.name = name;
this.summary = summary;
this.expectedJson = expectedJson;
this.actualJson = actualJson;
this.passed = expectedJson.equals(actualJson);
}
}
static String esc(String s) {
if (s == null) return "null";
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: sb.append(c);
}
}
sb.append("\"");
return sb.toString();
}
static String listJson(List<String> items) {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < items.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(esc(items.get(i)));
}
sb.append("]");
return sb.toString();
}
static String intListJson(List<Integer> items) {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < items.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(items.get(i));
}
sb.append("]");
return sb.toString();
}
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
this.val = x;
}
}
static void inorder(TreeNode node, List<Integer> out) {
if (node == null) return;
inorder(node.left, out);
out.add(node.val);
inorder(node.right, out);
}
static CaseResult testArraysAndLists() {
int[] arr = new int[5];
arr[0] = 10;
arr[4] = 50;
List<String> arrayList = new ArrayList<>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.add(20);
linkedList.addFirst(10);
linkedList.addLast(30);
String expected = "{\"arrLen\": 5, \"arrLast\": 50, \"arrayList\": [\"A\", \"B\", \"C\"], \"linkedList\": [10, 20, 30]}";
String actual = "{\"arrLen\": " + arr.length
+ ", \"arrLast\": " + arr[4]
+ ", \"arrayList\": " + listJson(arrayList)
+ ", \"linkedList\": " + intListJson(linkedList) + "}";
return new CaseResult(
"arrays_and_lists",
"验证定长数组随机访问、ArrayList 动态数组追加与 LinkedList 双向链表头尾插入",
expected,
actual
);
}
static CaseResult testSetsHashSetAndTreeSet() {
Set<String> hashSet = new HashSet<>(Arrays.asList("java", "go", "java", "rust"));
Set<Integer> treeSet = new TreeSet<>(Arrays.asList(30, 10, 20, 10));
boolean treeRejectsNull = false;
try {
treeSet.add(null);
} catch (NullPointerException e) {
treeRejectsNull = true;
}
List<Integer> sorted = new ArrayList<>(treeSet);
String expected = "{\"hashSetSize\": 3, \"treeSetSorted\": [10, 20, 30], \"treeRejectsNull\": true}";
String actual = "{\"hashSetSize\": " + hashSet.size()
+ ", \"treeSetSorted\": " + intListJson(sorted)
+ ", \"treeRejectsNull\": " + treeRejectsNull + "}";
return new CaseResult(
"sets_hashset_and_treeset",
"验证 HashSet 去重能力、TreeSet 红黑树自然排序去重以及禁止插入 null 元素",
expected,
actual
);
}
static CaseResult testMapsHashMapAndTreeMap() {
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("beta", 2);
hashMap.put("alpha", 1);
hashMap.put("alpha", 10);
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("c", 3);
treeMap.put("a", 1);
treeMap.put("b", 2);
List<String> orderedKeys = new ArrayList<>(treeMap.keySet());
String expected = "{\"hashMapAlpha\": 10, \"hashMapSize\": 2, \"treeMapKeys\": [\"a\", \"b\", \"c\"]}";
String actual = "{\"hashMapAlpha\": " + hashMap.get("alpha")
+ ", \"hashMapSize\": " + hashMap.size()
+ ", \"treeMapKeys\": " + listJson(orderedKeys) + "}";
return new CaseResult(
"maps_hashmap_and_treemap",
"验证 HashMap 键值覆盖与查找,以及 TreeMap 按键字典序有序遍历",
expected,
actual
);
}
static CaseResult testStackQueueAndHeaps() {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
List<Integer> lifo = Arrays.asList(stack.pop(), stack.pop(), stack.pop());
Queue<String> queue = new LinkedList<>();
queue.offer("first");
queue.offer("second");
Queue<String> deque = new ArrayDeque<>();
deque.offer("q1");
deque.offer("q2");
List<String> fifo = Arrays.asList(queue.poll(), queue.poll(), deque.poll());
PriorityQueue<Integer> minHeap = new PriorityQueue<>(Arrays.asList(5, 1, 3));
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.addAll(Arrays.asList(5, 1, 3));
String expected = "{\"lifo\": [3, 2, 1], \"fifo\": [\"first\", \"second\", \"q1\"], \"minTop\": 1, \"maxTop\": 5}";
String actual = "{\"lifo\": " + intListJson(lifo)
+ ", \"fifo\": " + listJson(fifo)
+ ", \"minTop\": " + minHeap.poll()
+ ", \"maxTop\": " + maxHeap.poll() + "}";
return new CaseResult(
"stack_queue_and_heaps",
"验证 Stack 后进先出、Queue(LinkedList/ArrayDeque)先进先出以及 PriorityQueue 最小堆与最大堆",
expected,
actual
);
}
static CaseResult testCustomTreeAndGraph() {
TreeNode root = new TreeNode(2);
root.left = new TreeNode(1);
root.right = new TreeNode(3);
List<Integer> treeOrder = new ArrayList<>();
inorder(root, treeOrder);
Map<String, List<String>> graph = new LinkedHashMap<>();
graph.put("A", Arrays.asList("B", "C"));
graph.put("B", Arrays.asList("D"));
graph.put("C", Collections.<String>emptyList());
graph.put("D", Collections.<String>emptyList());
List<String> bfs = new ArrayList<>();
Set<String> visited = new HashSet<>();
Queue<String> q = new ArrayDeque<>();
q.offer("A");
visited.add("A");
while (!q.isEmpty()) {
String cur = q.poll();
bfs.add(cur);
for (String nxt : graph.get(cur)) {
if (visited.add(nxt)) q.offer(nxt);
}
}
String expected = "{\"treeInorder\": [1, 2, 3], \"graphBfs\": [\"A\", \"B\", \"C\", \"D\"]}";
String actual = "{\"treeInorder\": " + intListJson(treeOrder)
+ ", \"graphBfs\": " + listJson(bfs) + "}";
return new CaseResult(
"custom_tree_and_graph",
"验证自定义二叉树节点 TreeNode 中序遍历以及基于邻接表实现的自定义图广度优先遍历",
expected,
actual
);
}
static CaseResult testLegacyStructuresSuite() {
Vector<String> vec = new Vector<>();
vec.add("v1");
vec.add("v2");
List<String> enumItems = new ArrayList<>();
Enumeration<String> en = vec.elements();
while (en.hasMoreElements()) {
enumItems.add(en.nextElement());
}
BitSet bs1 = new BitSet();
bs1.set(0);
bs1.set(2);
BitSet bs2 = new BitSet();
bs2.set(2);
bs2.set(3);
bs1.and(bs2);
Hashtable<String, String> ht = new Hashtable<>();
ht.put("100000", "Beijing");
boolean htIsDictionary = (ht instanceof Dictionary);
boolean htRejectsNull = false;
try {
ht.put(null, "bad");
} catch (NullPointerException e) {
htRejectsNull = true;
}
Properties props = new Properties();
props.setProperty("app.mode", "offline");
boolean sysPropsIsProperties = System.getProperties() instanceof Properties;
String expected = "{\"enumItems\": [\"v1\", \"v2\"], \"bit2\": true, \"bitCardinality\": 1, \"htIsDictionary\": true, \"htRejectsNull\": true, \"propMode\": \"offline\", \"sysPropsIsProperties\": true}";
String actual = "{\"enumItems\": " + listJson(enumItems)
+ ", \"bit2\": " + bs1.get(2)
+ ", \"bitCardinality\": " + bs1.cardinality()
+ ", \"htIsDictionary\": " + htIsDictionary
+ ", \"htRejectsNull\": " + htRejectsNull
+ ", \"propMode\": " + esc(props.getProperty("app.mode"))
+ ", \"sysPropsIsProperties\": " + sysPropsIsProperties + "}";
return new CaseResult(
"legacy_structures_suite",
"验证传统遗留类 Enumeration、BitSet、Vector、Dictionary、Hashtable 与 Properties 的核心行为",
expected,
actual
);
}
public static void main(String[] args) {
List<CaseResult> cases = Arrays.asList(
testArraysAndLists(),
testSetsHashSetAndTreeSet(),
testMapsHashMapAndTreeMap(),
testStackQueueAndHeaps(),
testCustomTreeAndGraph(),
testLegacyStructuresSuite()
);
StringBuilder out = new StringBuilder();
out.append("{\"version\": ").append(esc(System.getProperty("java.version"))).append(", \"cases\": [");
for (int i = 0; i < cases.size(); i++) {
CaseResult c = cases.get(i);
if (i > 0) out.append(", ");
out.append("{\"name\": ").append(esc(c.name))
.append(", \"summary\": ").append(esc(c.summary))
.append(", \"expected\": ").append(c.expectedJson)
.append(", \"actual\": ").append(c.actualJson)
.append(", \"passed\": ").append(c.passed)
.append("}");
}
out.append("]}");
System.out.println(out.toString());
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/java-data-structures-lab/ExploreDataStructures.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreDataStructures.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1111.zip
课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip