java集合 list、set、map能否存储null

java集合能否存储null

package com.idea.test.nulltest;

import jxl.common.Assert;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class NullTest {

public static void main(String[] args) {

    List list = new ArrayList();
    list.add(null);
    list.add(null);
    System.out.println("ArrayList :"+list.size());   //2


    List linkedList = new LinkedList();
    linkedList.add(null);
    linkedList.add(null);
    System.out.println("LinkedList :"+linkedList.size());  //2

    Set set=new HashSet();
    set.add(null);
    set.add(null);
   System.out.println("HashSet :"+set.size());// 1

    Set linkedHashSet=new LinkedHashSet();
    linkedHashSet.add(null);
    linkedHashSet.add(null);
    System.out.println("LinkedHashSet :"+linkedHashSet.size()); //1

    Set treeSet=new TreeSet();
    //treeSet.add(null);   //treeSet key不能null ava.lang.NullPointerException
    //treeSet.add(null);
   // System.out.println("TreeSet : "+treeSet.size());

    HashMap<String,String> map = new HashMap<>();
    map.put(null,null);
    map.put("liubei",null);
    System.out.println("HashMap :"+map.size());// 2

    LinkedHashMap linkedHashMap = new LinkedHashMap();
    linkedHashMap.put(null,null);
    linkedHashMap.put("liubei",null);
    System.out.println("LinkedHashMap :"+linkedHashMap.size()); //2

    TreeMap treeMap= new TreeMap<>();
    treeMap.put("liu",null);   //treeMap key  不能为空,value 可以为空
    //treeMap.put(null,"liubei");
    //treeMap.put(null,null);
    System.out.println("TreeMap :"+treeMap.size());

    Hashtable table=new Hashtable();
    //table.put("liu",null);  
    //table.put(null,"关羽");    //hashtable key与value均不能为空
    table.put(null,null);
    System.out.println("Hashtable"+table.size());

    ConcurrentHashMap concurrentHashMap=new ConcurrentHashMap();
    //concurrentHashMap.put("liu",null);    //concurrentHashmap key 与 value 均不可以为空
    //concurrentHashMap.put(null,"zhangfei");
    System.out.println("ConcurrentHashMap :"+concurrentHashMap.size());
}

}

1)、ArrayList、LinkedList 可以存储多个null (list.size()>1);

2)、HashMap、LinkedHashMap key 、value 都可以为null;TreeMap key 不能为null,value 可以为null;TreeSet 不能为null;

3)、HashSet、LinkedHashSet 不可重复集合,存储多个null时,list.size ==1(可存储一个null) ; TreeSet不能存入null;

4)、Hashtable、ConcurrentHashMap key与value均不能为null;

5)、TreeMap key 不能为null,value 可以为null;TreeSet 不能为null;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值