1. 程式人生 > 實用技巧 >java集合 list、set、map能否儲存null

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、vector、arraylist、linkedlist可以儲存多個null.

2、hashset、linkedset可以儲存一個null. treeset不能儲存null.

3、hashmap 、linkedhashmap key與value均可以為null. treemap key不可以為null,value可以為null. hashtable、concurrenthashmap key與value均不能為null.