Search code examples
javaclassobjectarraylistiterator

How to create Next() method in an Object class


I have a class called Tile that has the follow methods:

public Tile(Shape tile, Color color, int position), getTile(),

setTile(), getColor(), setColor(), getPosition(), setPosition()

Now using for(Tile item: tiles) I want to have a item.Next() that will move to the next index.

Btw tiles is List<Tile> tiles = new ArrayList<Tile> contains all the tiles, color and position.

So my question is how do I implement Next() in the Tile class? I can't do item++ since its of type Tile, etc.

Thanks for the help.

Note my Tile class and ArrayList tiles is located in different files


Solution

  • For loop also does the required as the below code,

    List<Tile> tiles = new ArrayList<Tile>();
    Iterator<Tile> tileIterator= tiles.iterator();
    while (tileIterator.hasNext()) {
         Tile tile = tileIterator.next();
         tile.setColor("green");
    }