• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why the need for two-step array initialization?  RSS feed

 
Tom Brodhead
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm making a generic stack using an array S[], and I don't understand why I have to initialize the S[] array in two steps. Here's my code (which works); questions and commentary below:




What I don't understand is why I can't initialize the array in one pass, like this:



Why must I create a local array (here simply named "array") and then assign S[] to the array?



If I don't do this, I receive a runtime error. But why?

~~Tom
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What exactly would that runtime error be?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm surprised it compiles at all even with the separation into two lines - an Object[] is not an E[], unless E is Object.

Why do you need to cast to E[] anyway? Your S is an Object[], and that's what you need to assign eventually. Why not just write "S = new Object[capacity]"?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tom Brodhead wrote:What I don't understand is why I can't initialize the array in one pass, like this:


Because then you are shadowing your instance field S with a local variable.

Why must I create a local array (here simply named "array") and then assign S[] to the array?


Because @SuppressWarnings works on variables, parameters, constructors / methods and classes. Not on statements. Now the annotation could have been applied to the instance field itself, but then all warnings for the field would be turned off throughout the entire class. The annotation could also have been applied to the constructor but again, the scope of the suppression is too great. By applying the annotation to only one single local variable which you discard immediately after you narrow the scope of the annotation to only those two lines. This will ensure that you do not suppress too many warnings.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!