当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Object array is filled with all the same values

问题描述:

i have created a class called BingoCard and i am trying to fill an array of "BingoCard"s with BingoCard dataTypes in a constructor in a new class called BingoGame

public BingoGame(int numberOfCards)

{

bingoCardArray = new BingoCard[numberOfCards];

BingoCard card = new BingoCard();

for(int i=0;i<numberOfCards;i++)

{

card.fillCard();

bingoCardArray[i] = card;

}

//numbers that have been called

numbersCalled = new ArrayList<Integer>();

}

for some reason it fills the array with the same BingoCard value in each index of the array which is the last value that was entered in the array. For example it fills index 0 with BingoCard of value (A) and at the end of the loop it fills index 5 with BingoCard of value (F) now all indexes of the array contain the value (F). Any ideas why this is happening?

(The card.fillCard() has been tested and works i.e it changes the value of the BingoCard each time)

网友答案:

You should create the instances inside the loop :

for(int i=0;i<numberOfCards;i++)
{
    BingoCard card = new BingoCard();
    card.fillCard();
    bingoCardArray[i] = card;
}

If you create just one instance of BingoCard before the loop, all the positions in the array would contain the same instance.

分享给朋友:
您可能感兴趣的文章:
随机阅读: