-1

Hashtable does not allow any null as key or value, and Hashtable is legacy and only single thread can access at a time.

Which collection class doesn't allow any null and allows concurrent access?

This question is asked in an interview, what would be the possible answer?

surya prakash
  • 49
  • 1
  • 5

2 Answers2

0
ConcurrentHashMap

There you go.

For differences between HashTable and ConcurrentHashMap, I'd suggest you read ConcurrentHashMap and Hashtable in Java

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
  • You missed ConcurrentSkipListMap: "Like most other concurrent collections, this class does not permit the use of null keys or values because some null return values cannot be reliably distinguished from the absence of elements" https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListMap.html – JL_SO Jul 27 '18 at 14:05
  • And ConcurrentSkipListSet https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListSet.html – JL_SO Jul 27 '18 at 14:11
0

Both the ConcurrentHashMap and Hashtable doesn't allow any null key and allows concurrent access.

  • ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java, which is a synchronized collection class(thread-safe). It provides full concurrency of retrievals (as the get operation does not entail locking) and high expected concurrency of updates.
  • The Hashtable class is mostly considered obsolete. It is a thread-safe hash map, but unlike ConcurrentHashMap, all its methods are simply synchronized, which means that all operations on this map block, even retrieval of independent values

Ex:-

Map<Integer, String> ch = new ConcurrentHashMap<Integer, String>();
ch.put(1, "First");
ch.put(2, "Second");
ch.put(null, "value"); //throws java.lang.NullPointerException
ch.forEach((k,v) -> System.out.println("Key = "  + k + ", Value = " + v));

For the difference between HashMap and ConcurrentHashMap refer this. Helpful thread from Stack Overflow found here.

SkPuthumana
  • 73
  • 1
  • 7