蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Java 8 集合框架接口、标准/遗留实现、四种 Map 遍历与算法比较器实测

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreCollections.java
ExploreCollections.java379 行
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;

public class ExploreCollections {
    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 '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); 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;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private static boolean testUnmodifiableEmptyList() {
        try {
            List emptyList = Collections.EMPTY_LIST;
            emptyList.add("x");
            return false;
        } catch (UnsupportedOperationException ex) {
            return true;
        }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private static boolean testIncompatibleSort() {
        try {
            List raw = new ArrayList(Arrays.asList("text", Integer.valueOf(42)));
            Collections.sort(raw);
            return false;
        } catch (ClassCastException ex) {
            return true;
        }
    }

    public static void main(String[] args) {
        List<Map<String, Object>> cases = new ArrayList<Map<String, Object>>();

        // Case 1: List vs Set vs SortedSet vs Map vs SortedMap core interfaces
        {
            List<String> list = new ArrayList<String>(Arrays.asList("B", "A", "B"));
            Set<String> set = new HashSet<String>(list);
            SortedSet<String> sortedSet = new TreeSet<String>(Arrays.asList("C", "A", "B"));
            SortedMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
            sortedMap.put("k2", 2);
            sortedMap.put("k1", 1);

            List<String> expectedList = Arrays.asList("B", "A", "B");
            List<String> expectedSortedSet = Arrays.asList("A", "B", "C");
            List<String> expectedSortedKeys = Arrays.asList("k1", "k2");

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("list_order_and_dup", expectedList);
            expected.put("set_unique_size", 2);
            expected.put("sorted_set", expectedSortedSet);
            expected.put("sorted_map_keys", expectedSortedKeys);

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("list_order_and_dup", list);
            actual.put("set_unique_size", set.size());
            actual.put("sorted_set", new ArrayList<String>(sortedSet));
            actual.put("sorted_map_keys", new ArrayList<String>(sortedMap.keySet()));

            cases.add(makeCase(
                "collection_set_list_map_interfaces",
                "验证 List 有序可重复、Set 去重、SortedSet 排序与 SortedMap 键升序特性",
                expected,
                actual
            ));
        }

        // Case 2: Standard implementations, synchronizedList, LinkedHashSet/LinkedHashMap, IdentityHashMap, WeakHashMap
        {
            List<String> syncLinked = Collections.synchronizedList(new LinkedList<String>());
            syncLinked.add("first");
            syncLinked.add(null);
            syncLinked.add("last");

            Set<String> linkedSet = new LinkedHashSet<String>();
            linkedSet.add("z");
            linkedSet.add("a");
            linkedSet.add("m");

            Map<String, Integer> linkedMap = new LinkedHashMap<String, Integer>();
            linkedMap.put("third", 3);
            linkedMap.put("first", 1);
            linkedMap.put("second", 2);

            Map<String, String> idMap = new IdentityHashMap<String, String>();
            String k1 = new String("token");
            String k2 = new String("token");
            idMap.put(k1, "v1");
            idMap.put(k2, "v2");

            Map<Object, String> weakMap = new WeakHashMap<Object, String>();
            Object strongRef = new Object();
            weakMap.put(strongRef, "alive");

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("sync_linked_size", 3);
            expected.put("sync_linked_has_null", true);
            expected.put("linked_set_order", Arrays.asList("z", "a", "m"));
            expected.put("linked_map_insertion_order", Arrays.asList("third", "first", "second"));
            expected.put("identity_map_distinct_refs", 2);
            expected.put("weak_map_strong_entry", "alive");

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("sync_linked_size", syncLinked.size());
            actual.put("sync_linked_has_null", syncLinked.contains(null));
            actual.put("linked_set_order", new ArrayList<String>(linkedSet));
            actual.put("linked_map_insertion_order", new ArrayList<String>(linkedMap.keySet()));
            actual.put("identity_map_distinct_refs", idMap.size());
            actual.put("weak_map_strong_entry", weakMap.get(strongRef));

            cases.add(makeCase(
                "standard_implementations_and_sync",
                "验证 Collections.synchronizedList(new LinkedList<>())、LinkedHashSet/LinkedHashMap 插入序、IdentityHashMap 引用相等及 WeakHashMap",
                expected,
                actual
            ));
        }

        // Case 3: Legacy java.util classes (Vector, Stack, Hashtable, Properties, BitSet, Enumeration)
        {
            Vector<String> vec = new Vector<String>(Arrays.asList("v1", "v2"));
            List<String> enumItems = new ArrayList<String>();
            Enumeration<String> en = vec.elements();
            while (en.hasMoreElements()) {
                enumItems.add(en.nextElement());
            }

            Stack<String> stack = new Stack<String>();
            stack.push("bottom");
            stack.push("top");
            String popped = stack.pop();

            Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
            ht.put("port", 8080);

            Properties props = new Properties();
            props.setProperty("mode", "offline");

            BitSet bs = new BitSet();
            bs.set(1);
            bs.set(3);

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("enumeration_items", Arrays.asList("v1", "v2"));
            expected.put("stack_lifo_pop", "top");
            expected.put("hashtable_port", 8080);
            expected.put("properties_mode", "offline");
            expected.put("bitset_cardinality", 2);

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("enumeration_items", enumItems);
            actual.put("stack_lifo_pop", popped);
            actual.put("hashtable_port", ht.get("port"));
            actual.put("properties_mode", props.getProperty("mode"));
            actual.put("bitset_cardinality", bs.cardinality());

            cases.add(makeCase(
                "legacy_util_classes_and_enumeration",
                "验证传统集合 Vector、Enumeration、Stack、Hashtable、Properties 与 BitSet 的基础行为",
                expected,
                actual
            ));
        }

        // Case 4: Three ArrayList traversal methods & ListIterator bidirectional traversal
        {
            List<String> list = new ArrayList<String>(Arrays.asList("Hello", "World", "Java"));
            List<String> viaForEach = new ArrayList<String>();
            for (String s : list) {
                viaForEach.add(s);
            }
            String[] arr = new String[list.size()];
            list.toArray(arr);
            List<String> viaArray = Arrays.asList(arr);

            List<String> viaIterator = new ArrayList<String>();
            Iterator<String> it = list.iterator();
            while (it.hasNext()) {
                viaIterator.add(it.next());
            }

            List<String> reverseViaListIterator = new ArrayList<String>();
            ListIterator<String> lit = list.listIterator(list.size());
            while (lit.hasPrevious()) {
                reverseViaListIterator.add(lit.previous());
            }

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("foreach", Arrays.asList("Hello", "World", "Java"));
            expected.put("array", Arrays.asList("Hello", "World", "Java"));
            expected.put("iterator", Arrays.asList("Hello", "World", "Java"));
            expected.put("list_iterator_reverse", Arrays.asList("Java", "World", "Hello"));

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("foreach", viaForEach);
            actual.put("array", viaArray);
            actual.put("iterator", viaIterator);
            actual.put("list_iterator_reverse", reverseViaListIterator);

            cases.add(makeCase(
                "traverse_arraylist_and_listiterator",
                "验证 ArrayList 的增强 for、toArray 数组与 Iterator 三种遍历及 ListIterator 反向遍历",
                expected,
                actual
            ));
        }

        // Case 5: Four Map traversal strategies
        {
            Map<String, String> map = new LinkedHashMap<String, String>();
            map.put("1", "value1");
            map.put("2", "value2");
            map.put("3", "value3");

            List<String> byKeySet = new ArrayList<String>();
            for (String k : map.keySet()) {
                byKeySet.add(k + "=" + map.get(k));
            }
            List<String> byEntryIterator = new ArrayList<String>();
            Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> e = it.next();
                byEntryIterator.add(e.getKey() + "=" + e.getValue());
            }
            List<String> byEntryForEach = new ArrayList<String>();
            for (Map.Entry<String, String> e : map.entrySet()) {
                byEntryForEach.add(e.getKey() + "=" + e.getValue());
            }
            List<String> byValues = new ArrayList<String>(map.values());

            List<String> expectedPairs = Arrays.asList("1=value1", "2=value2", "3=value3");
            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("keyset", expectedPairs);
            expected.put("entry_iterator", expectedPairs);
            expected.put("entry_foreach", expectedPairs);
            expected.put("values", Arrays.asList("value1", "value2", "value3"));

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("keyset", byKeySet);
            actual.put("entry_iterator", byEntryIterator);
            actual.put("entry_foreach", byEntryForEach);
            actual.put("values", byValues);

            cases.add(makeCase(
                "traverse_map_four_ways",
                "验证 Map 的 keySet、entrySet 迭代器、entrySet 增强 for 与 values 四种遍历方式",
                expected,
                actual
            ));
        }

        // Case 6: Collection algorithms, immutable empty constants, Comparator sorting
        {
            List<String> words = new ArrayList<String>(Arrays.asList("pear", "fig", "apple", "kiwi"));
            Collections.sort(words, new Comparator<String>() {
                @Override
                public int compare(String a, String b) {
                    int lenDiff = Integer.compare(a.length(), b.length());
                    return lenDiff != 0 ? lenDiff : a.compareTo(b);
                }
            });

            TreeSet<String> revSet = new TreeSet<String>(Collections.reverseOrder());
            revSet.addAll(Arrays.asList("alpha", "gamma", "beta"));

            boolean unsupportedThrown = testUnmodifiableEmptyList();
            boolean classCastThrown = testIncompatibleSort();

            Map<String, Object> expected = new LinkedHashMap<String, Object>();
            expected.put("comparator_sorted", Arrays.asList("fig", "kiwi", "pear", "apple"));
            expected.put("treeset_reverse", Arrays.asList("gamma", "beta", "alpha"));
            expected.put("empty_constants_sizes", Arrays.asList(0, 0, 0));
            expected.put("unmodifiable_throws_uoe", true);
            expected.put("incompatible_sort_throws_cce", true);

            Map<String, Object> actual = new LinkedHashMap<String, Object>();
            actual.put("comparator_sorted", words);
            actual.put("treeset_reverse", new ArrayList<String>(revSet));
            actual.put("empty_constants_sizes", Arrays.asList(
                Collections.EMPTY_LIST.size(),
                Collections.EMPTY_SET.size(),
                Collections.EMPTY_MAP.size()
            ));
            actual.put("unmodifiable_throws_uoe", unsupportedThrown);
            actual.put("incompatible_sort_throws_cce", classCastThrown);

            cases.add(makeCase(
                "collection_algorithms_and_comparator",
                "验证 Collections 排序算法、Comparator 自定义排序、EMPTY 不可变集合异常及类型不兼容 ClassCastException",
                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-collections-lab/ExploreCollections.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreCollections.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Java

课程关联工程包(登记关联57章) · 含当前章节或实例 · mbskycom202612a1104.zip

下载课程关联工程包:Java

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1108.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习