Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Defining an empty array

 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java compiler allows this:

It has length zero and as arrays cannot be resized could it ever have any possible purpose?
 
Henry Wong
author
Marshal
Pie
Posts: 22106
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steffe Wilson wrote:
It has length zero and as arrays cannot be resized could it ever have any possible purpose?


Sure. Why not? Let's say you have a method that returns some membership to something in an array -- and there are no members.


And a classic case is the main() method. If you call your program with no parameters, the JVM will pass in an zero length string array for the arguments.

Henry
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those are v. good examples, thanks Henry. I wasn't thinking outside the box!

 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steffe Wilson wrote:It has length zero and as arrays cannot be resized could it ever have any possible purpose?

And what about thisAnd then you can invoke this method with a variable number of arguments and even noneIn the latter case an array with zero elements will be created as well.

In the Java API you have similar methods, one of the most used ones is probably the Arrays.asList(T... a) method.

Hope it helps!
Kind regards,
Roel
 
Steffe Wilson
Ranch Hand
Posts: 165
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Roel, yes that helps & its another interesting example.
Cheers.


 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And a method which converts a collection of objects into an array of objects might return an empty array (if the list is empty). For String this method might look likeSo there actually a lot of purposes of using an empty array. I think the most common ones are already mentioned: the string array parameter of the main() method (if you invoke your program with no parameters) and the var-args parameter.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic