0

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.

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

2
  • 2
    Consider Arrays.fill(gems, new Gem());. In this line you create a single gem, and use the same gem to fill the array. Have you considered using a for loop instead? Commented May 10, 2015 at 22:34
  • Use Arrays.setAll. Commented May 10, 2015 at 22:36

1 Answer 1

2

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:

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].

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, yes, in my current version of the code I already use a two dimensional Object array, but thanks anyway :)
setAll doesn't seem to exist for Object @BoristheSpider
@RichardKoetschruyter it does. I linked to it.
mmm not sure about that. You would be surprised how much Java 6 and 7 is still out there.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.