Search code examples
javaarraysobjectarraylistinstance

How do I return a specific object from an ArrayList?


So I'm trying to implement a method in a Grid class that returns the tile (which is an instance of the tile class) specified by two coordinates the user inputs. But I have no idea how to go about implementing it.

I have an ArrayList that contains all the instances of the tiles like this tiles.add(new Tile(x, y));

This is the method in question and my attempt at returning the desired tile:

   public ArrayList<Tile> getTileAtPos(int xCoor, int yCoor) {
        // if the coordinates are out of bounds
        // return null;

        // else
        return tiles.get(/*???*/); //   <---------------------- have no clue
    }

Solution

  • I recommend you reading on the documentation.

    Anyway if you don't want to, the explanation is that the get() method for ArrayList uses the index to return the object.

    ArrayList is not a Dictionary/Map based data structure where it has raw functions to compare based on object similarity.

    The following when compared to arrays:

    int_arr[2]; // some number
    

    versus

    int_arraylist.get(2); // some number
    

    Are the exact same.

    If you want to find an element based on ITS RAW PROPERTIES, in this case your xCoords and yCoords. Then you have to use a loop to check the individual elements in the ArrayList if they match the properties. Something like this:

    if(xCoord > boundX || yCoord > boundY) {
        return null;
    }
    for(Tile e : tiles) {
        if(e.xCoord == xCoord && e.yCoord == yCoord) // change to match your accessor methods or however you access the x and y
            return e;
    }
    return null;
    

    Hope this helps!