-10

We can put single null key in hashMap. but in linkedHashMap we can't pull null key. what is the reason behind this.

Shivam
  • 9
  • 2
  • 5
  • 1
    Where have you read that "in linkedHashMap that we can't pull null key."? What do you mean by "single" null key ? – davidxxx Apr 25 '17 at 09:13
  • Null keys are allowed in all the maps, not just HashMap. – iavanish Apr 25 '17 at 09:14
  • You can assign null for all map as a key. Follow the @assylias answer. – Simmant Apr 25 '17 at 09:15
  • @iavanish That isn't true, `TreeMap` will happily refuse `null` keys in certain cases. – biziclop Apr 25 '17 at 09:16
  • @biziclop Yes, you are right (in certain cases TreeMap will produce null pointer exception). If your keys' Comparator does not permit null values or it is based on natural ordering, then it won't allow null keys. But if you create custom Comparator that does allow null values, the map will also allow null keys. From the Java Doc, "throws NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys". – iavanish Apr 25 '17 at 09:33
  • In Interview they asked me this question. I have to research before posting this questions. And also i am beginner in stackoverflow, next time i will take care. – Shivam Apr 25 '17 at 10:03
  • @Shivam Don't despair, and next time this happens, make sure you mention in the question that it was an interview question. – biziclop Apr 25 '17 at 10:14

2 Answers2

10

You can put a null key in a LinkedHashMap. Example:

Map<String, String> m = new LinkedHashMap<> ();
m.put(null, "a");
System.out.println(m.size());
System.out.println(m.get(null));

prints 1 and a.

assylias
  • 321,522
  • 82
  • 660
  • 783
3

Following documentation

This class provides all of the optional Map operations, and permits null elements.

sovas
  • 1,508
  • 11
  • 23