使用新对象填充对象数组

时间:2020-11-29 20:10:32

I'm trying to populate an object array with new objects. Here is the code:

我正在尝试使用新对象填充对象数组。这是代码:

Main class

public class Bejeweled extends JFrame{

public Bejeweled(){
    Board board = new Board();
    getContentPane().add(board);
    board.start();
}

public static void main(String[] args){
    Bejeweled game = new Bejeweled();
}

Board class

public class Board extends JPanel{

final int BOARDHEIGHT = 8;
final int BOARDWIDTH = 8;
Gem[] gems;

public Board(){
    gems = new Gem[BOARDHEIGHT * BOARDWIDTH];
}

public void start(){
    fillBoard();
}

public void fillBoard(){
    Arrays.fill(gems, new Gem());
    for(Gem gem : gems){
        System.out.println(gem.type); //**This was expected to print random numbers**
    }
}
}

Gem class

public class Gem {

public int type;

public Gem(){
    this.type = genType();
}

public int genType(){
    return (int) (Math.random() * 7);
}

}

The problem is that all objects appear to be the same. I know I should encapsulate type in the Gem class, but I'm trying to limit the amount of code I'm posting here.

问题是所有对象看起来都是一样的。我知道我应该在Gem类中封装类型,但我试图限制我在这里发布的代码量。

A new Board gets created from the main class, in the Board class a Gem[] is filled with newly created Gems (class Gem).

从主类创建一个新的Board,在Board类中,Gem []充满了新创建的Gems(类Gem)。

1 个解决方案

#1


Arrays.fill fills the array with the value you provide, which in this case is a particular instance of Gem. Instead, you need to use a for loop and set each of the array elements to a distinct Gem:

Arrays.fill用您提供的值填充数组,在这种情况下,它是Gem的特定实例。相反,您需要使用for循环并将每个数组元素设置为不同的Gem:

for(int i = 0; i < gems.length; i++) {
    gems[i] = new Gem();
}

Note that if you really have an 8x8 board, it's much preferable to have a Gem[8][8] than a Gem[8*8].

请注意,如果你真的有8x8板,那么Gem [8] [8]比Gem [8 * 8]更可取。

#1


Arrays.fill fills the array with the value you provide, which in this case is a particular instance of Gem. Instead, you need to use a for loop and set each of the array elements to a distinct Gem:

Arrays.fill用您提供的值填充数组,在这种情况下,它是Gem的特定实例。相反,您需要使用for循环并将每个数组元素设置为不同的Gem:

for(int i = 0; i < gems.length; i++) {
    gems[i] = new Gem();
}

Note that if you really have an 8x8 board, it's much preferable to have a Gem[8][8] than a Gem[8*8].

请注意,如果你真的有8x8板,那么Gem [8] [8]比Gem [8 * 8]更可取。