• Post Reply Bookmark Topic Watch Topic
  • New Topic

Initializing an array in a constructor  RSS feed

 
Miles Davis
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question about how to construct an array in a constructor.

The following compiles:






However, the following does not compile.



Why isn't this valid? Is it possible to use the curly brackets for initializing an array in a constructor?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can only use the array literal notation in an initializer, not in an assignment.

Valid:


Not valid:
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this is valid:-
int[] numbers = new int[]{1, 2, 3,};
Think of that as the normal way to write an array initialiser, but you may miss out
new int[]
only if you have the declaration and initialisation together.
If possible use initialisers rather thanbecause you can always be sure the size of the array will be exactly right for the contents.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!