JAVA中哪些集合允许key为null
Hashtable、ConcurrentHashTable,TreeMap不允许key为null,编译运行时会提示空指针异常。
HashSet 、HashMap 、 ArrayList 、 LinkedList均可接受null值
public static void main(String[] args) { /* TreeMap<Object, Object> map = new TreeMap<>(); map.put(null, 1);*/ /* TreeSet<Object> objects = new TreeSet<>(); objects.add(null);*/ /* ConcurrentHashMap<Object, Object> a = new ConcurrentHashMap<>(); a.put(null, 1);*/ HashSet<Object> objects1 = new HashSet<>(); objects1.add(null); System.out.println(objects1.size()); HashMap<Object, Object> objectObjectHashMap = new HashMap<>(); objectObjectHashMap.put(null, 1); System.out.println(objectObjectHashMap.size()); ArrayList<Object> objects = new ArrayList<>(); objects.add(null); System.out.println(objects.size()); LinkedList<Object> objects2 = new LinkedList<>(); objects2.add(null); System.out.println(objects2.size()); //长度为1 System.out.println(objects2.get(0)); //值为null }