0

I'm working with a double array and need to be able to calculate the surrounding <8 neighbors of one tile from class Tile. Since I want to know them individually, Tile contains 8 setter-methods that accept Tile as a parameter for every direction respectively. So first I'm iterating through the neighbors of a given tile and add them to an ArrayList. Now I want to pass those elements into the setter-methods but they won't accept it because it's not a Tile but a List<Tile> How can I work around this? I tried changing the setter-Method to expect a List but that didn't change anything. Or do I maybe need to restructure my entire approach? For this I was looking at a tile that definitely had all 8 neighbors, I need to think of catching those at the edge who don't have as much neighbors once this works in general.

private void calculateNeighbors (int x, int y){
    System.out.print("The neighbors of " + getTile(x,y));

    List<Tile> neighbors = new ArrayList<>();

    int[] coordinates = new int[]{
            -1,-1, 
            -1, 0,
            -1, 1,
            0,-1,
            0, 1,
            1,-1,
            1, 0,
            1, 1
    };

    for (int i = 0; i < coordinates.length; i++) {
        int columnX = coordinates[i];
        int rowY = coordinates[++i];

        int nextX = x + columnX;
        int nextY = y + rowY;

        if (nextX >= 0 && nextX < getListOfTiles().length
                && nextY >= 0 && nextY < getListOfTiles().length) {
                neighbors.add(getTile(nextX, nextY));
        }
    }
    //this here isn't working
    tile.setTopLeft(neighbors[0]);
    tile.setTop(neighbors[1]);
    //etc
    }
}

1 Answer 1

1

You need to use the get(int) method of a list to access objects in the list based on their index.

tile.setTopLeft(neighbors.get(0));
tile.setTop(neighbors.get(1));

Subscript operator is when you have an array.

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

3 Comments

thanks! Syntax is okay now, I'm still getting a null pointer though. Any idea why? When I print the list it's not empty, it's got 8 elements but when I try to access them like you showed me, there's nothing there
Can you paste the code where your getting null pointer? Have an edit section in your question to paste the code where your trying to access it and getting NPE.
think my problem is a different one altogether but maybe you've got a clue

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.