Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Stupid question about initializing arrays

 
Craig Flannagan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the most slickest way to initialize arrays (which are attributes) in a constructor?
For example, the following code does not work:

So I have to do the following instead:

Two questions:
Was the 2nd code snipplet the best "professional" way to do it?
And why wouldn't the first code snipplet work, even though I can do it if I declare an array and initialize all on a single line?
Many thanks!
CF
[ April 25, 2002: Message edited by: Craig Flannagan ]
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
well i woudlnt do it the second way.. just doesnt sem that professional tome but i may be wrong.
If you really want to intialize it why not like you said just do it at the first line when you define th e variable too.
like:
int[] numbers={4,5,6,7}
what diffrence does it make if you put it in the constructor or not?
the intialization will take place anyway every time you create an object.
thats how i would do it anyway, but im sure a bartendar here will answer a better reply.
 
Craig Flannagan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, bad example.
What about this scenario:
Declaring array as an attribute (no initialization)...
And then initialize the array in the constructor with values passed as arguements...
How would you handle this?
Thanks,
CF
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmm.
i see your point.
in that case i would do exactly as you did.
maybe just as a precaution you could also set the temp array at the end to null just to make sure you dont have 2 refercnes to it. although in this case because its a local variable it will get deleted anyway.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this:
 
Craig Flannagan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim Yingst -
That's the first time I've seen anything of that sort. Thanks for the education!
-CF
[ April 25, 2002: Message edited by: Craig Flannagan ]
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow!
same here.
thanks Jim.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic