Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array object initialization

I just want ask, is it possible to initiliaze more objects with same constructor in one command?

Example of code:

Tile[] tiles = new Tile(5,5)[20];

Thanks for response.

like image 589
user2899587 Avatar asked Feb 17 '14 03:02

user2899587


1 Answers

Impossible as far as I know. The code Tile[] tiles = new Tile[20]; just creates an array of references. To fill the array, you should create a Tile object and then assign the reference to one index of the array, such as:

tiles[0] = new Tile(5,5);

If all elements of the array pointing to the same object is OK, you can full fill the array simply use:

Tile tiles = new Tile[20];
Arrays.fill(tiles, new Tile(5,5));
like image 173
Weibo Li Avatar answered Oct 02 '22 16:10

Weibo Li