JAVA中哪些集合允许value为null

Hashtable(k,v都不允许为null)、ConcurrentHashTable(k,v都不允许为null),ConcurrentHashMap(k,v都不允许为null),TreeMap不允许key为null,但是value可以为null。TreeSet不能为null,因为要排序

HashSet 、HashMap 、 ArrayList 、 LinkedList均可接受null值(有key的指的是key)

HashMap允许value为null,ArrayList允许多个null值,HashSet允许单个null值

 // 1. HashMap允许value为null
        System.out.println("==== HashMap测试 ====");
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", null);
        hashMap.put("key2", "正常值");
        hashMap.put(null, "key为null");
        System.out.println("key1的值: " + hashMap.get("key1"));
        System.out.println("null键的值: " + hashMap.get(null));

        // 2. ArrayList允许多个null值
        System.out.println("\n==== ArrayList测试 ====");
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("正常元素");
        arrayList.add(null);
        arrayList.add(null);
        arrayList.forEach(item ->
                System.out.println(item == null ? "null元素" : item)
        );

        // 3. HashSet允许单个null值
        System.out.println("\n==== HashSet测试 ====");
        HashSet<String> hashSet = new HashSet<>();
        hashSet.add(null);
        hashSet.add("非空元素");
        System.out.println("集合包含null? " + hashSet.contains(null));

        // 4. Hashtable禁止null值(对比实验)
        System.out.println("\n==== Hashtable测试 ====");
        try {
            Hashtable<String, String> hashtable = new Hashtable<>();
            hashtable.put("key", null);
        } catch (NullPointerException e) {
            System.out.println("Hashtable抛异常: " + e.getClass().getSimpleName());
        }
posted @ 2025-08-27 17:05  朝阳1  阅读(24)  评论(0)    收藏  举报