简体   繁体   中英

Casts in 2D object array in Java

I'm working on a checkers game in java. I'm representing my board like this:

Object[][] board = new Object[8][8];

I want to be able to place a Checker object or a null value in the 2D Object Array.

I have a method that assigns Checker objects to locations in the 2D object array.

My problem is, when I go to write my test for the method:

    public void testPopulateCheckers() {
        assertEquals("Red", game.board[0][4].color)
    }

The color method (which is a method for my Checker class) does not show up. I've tried casting it as a Checker ,but it only lists the Object methods available.

// This should work
public void testPopulateCheckers() {
    assertEquals("Red", ((Checker) game.board[0][4]).color)
}

However, if all you are storing are Checker objects or null, change your declaration to this so you do not have to cast.

Checker[][] board = new Checker[8][8];

You should use Checker to declare your matrix if you expect to call a method like color() on it.

Checker[][] board = new Checker[ 8 ][ 8 ];

and of course make sure that you initialize all of the 64 Checkers since only the board is initialized by the line above.

Define your matrix like this..

Object[][] board = new Checker[8][8];

public void testPopulateCheckers() {
    assertEquals("Red", ((Checker) game.board[0][4]).color)
}

You need to cast it.

EDIT : method added!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM