• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array of zero length  RSS feed

 
Mohan Chandrasekaran
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am interested to know the array of length zero will be created? What will be nature of array object created in Heap?
 
Scott Selikoff
author
Bartender
Posts: 4093
21
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mohan Chandrasekaran:
I am interested to know the array of length zero will be created? What will be nature of array object created in Heap?


The array of length zero can't hold data, so as a source of data it is not very helpful. What it's better for is as a replacement to sending null pointers. For example, consider the following loop (in java 1.4 format):



Now, if the array is empty or null, you would expect no work to be done in the loop. But if the array is null, it will actually through a null pointer exception on x.length, whereas an empty array would just skip the loop so the empty array simplifies a lot of logic and avoids excessive null pointer checks.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, an empty array is just another array, allocated on the heap like any object.

The previous poster also talks about something that is detailed
in Joshua Bloch's Effective Java:
Item 27: return zero-length arrays, not nulls.
Here is a pdf of chapter 6 of that book, where item 27 is discussed.
 
Mohan Chandrasekaran
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot friends for the reply..
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!