Skip to content
Advertisement

How do I work with objects in lists and can I create multiple objects with different names in a loop?

I need to create Objects of a class called “Tile”. I have 9×9 chess board like grid and want to initiate the whole board at once. The position of a Tile is defined by an x and y-axis and I need to work with those later.

I thought about doing it with a loop but I want each object to have different names if that is possible.

The following code works for creating a List and filling it with the Objects I need. My question is, how can I work with Elements in that list? tileList.get("index")."attribute"doesn’t work.

Every advice on how you would do it in a different way is appreciated, as I am really trying to learn.

public class Main {

    public static void main(String[] args) {

        List<Tile> tileList = new ArrayList<Tile>(9);

    //These loops just set the values for the Coordinates
    //a total of 9 Objects is created    
        for(int i = 1; i<4; i++) {
            for(int j = 1; j<4; j++) {
                
            Tile t = new Tile(i,j);
            tileList.add(t);
        }

Advertisement

Answer

Lists are not like normal array , its mutable , you don’t need to specify your list length , so you can declare a list simply like :

List<Tile> tiles = new ArrayList<>(); 
//then you fill it using nested for 
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
tiles.add(new Tile(i,j));
}
}

your list now should have 9 point of (x,y) pair , thier value is : (0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)

you can access a specific item by using :

Tile myTile = tiles.get(yourIndex);

if your Tile class has a property x , you can get it like :

int x = myTile.getX();

Note : I assumed that you have getters in your Tile class .

You can check this simple tutorial to better understand of how lists works .

Advertisement