Inserting null values in TreeSet and HashSet:

For an Empty TreeSet as first element null value can be inserted but after inserting that first value if we are trying to insert any other objects then we will get NullPointerException.For an non empty TreeSet if we are trying to inser null value at run time u will get nullPointerException. This is because when some elements are there in the tree then before inserting any object it compares the new object to the existing ones by the compareTo() method and decides where to put the new object. So when inserting null the compareTo() method internally throws  NullPointerException.

For HashSet only one null value insertion is possible. When we try to add more null values the add method returns false and null is not added.

5 comments:

  1. TreeSet Doesn't Allow null values anywhere

    ReplyDelete
  2. TreeSet Doesn't Allow null values anywhere

    ReplyDelete
  3. Till 1.6 version , insertion of null in non empty TreeSet is acceptable, but 1.7 version onward ,its non acceptable

    ReplyDelete
  4. For empty TreeSet as first element null is allowed but this rule is applicable till 1.6v only. 1.7v onwards null is not allowed even as the first element.

    ReplyDelete
  5. I have a query if TreeSet allows null as first element then when second element gets added does it not compare new value with null stored?

    ReplyDelete