Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why Null value is allowed in ArrayList,Vector,Set or HashMap?  RSS feed

 
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Why null values are allowed in Set,Vector ,List.

and one Null key is allowed in HashMap.

Regards,
Prabhat
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because I may need null values in a Collection. For instance, I may have static positions (say seats around a poker table) and I need to sometimes have values matching those keys and other times I need to have null values there (for instance no player is seated in the poker table's seat at static position 'n' so don't deal to that position).

There are many times that being able to put null values into Collections is very useful.
 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes that's true.

means if we want to check if the list has null value or something list that in our real world object. We need to use the Null object.

and why HashTable doesn't allow null key while HashMap allows?
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Prabhat Ranjan wrote:and why HashTable doesn't allow null key while HashMap allows?


Dunno. Probably something to do with how it works internally.

And strictly speaking, the restriction is not particularly important. In the case of Alvin's Poker game, it would be perfectly easy (and probably clearer) to create a Player that signifies an empty seat, viz:
public static final Player EMPTY_SEAT = new Player("Not-A-Player");

Personally, I try to avoid using nulls whenever possible.

Winston
 
Marshal
Posts: 58378
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Prabhat Ranjan wrote: . . . We need to use the Null object. . . .

What’s a Null object? Do you mean the null literal? That points to no object at all, so there is no such thing as a null object.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!