No, this is not possible, because an enhanced for
loop will give a reference to the current element. Assigning a new object to the reference won't assign the element to the array. There is no substitute for using an array access expression to assign an element to an array.
You can use two "traditional" for
loops with an array access expression to initialize the array.
for (int s = 0; s < SUITS; s++)
for (int c = 0; c < RANKS; c++)
cards[s][c] = new Card(...);
It's possible to use an array initializer, but it would tedious, excessively verbose, and error-prone.
cards = new Card[][] {
{new Card(...), new Card(...), ... },
{new Card(...), new Card(...), ... },
...};
Interestingly, because the 2D array is implemented as an array of arrays, and array references are used, the outer array can be initialized with an enhanced for
loop, as long as the inner array is initialized with a "traditional" loop. This works because suit
is an array in cards
, so suit[c]
is an element in cards
.
cards = new Card[SUITS][RANKS];
for(Card[] suit : cards) {
for(int c = 0; c < RANKS; c++) {
suit[c] = new Card(suitVar, rankVar);
}
}