evgeni mironov
evgeni mironov

Reputation: 35

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

Upvotes: 0

Views: 374

Answers (3)

Thush-Fdo
Thush-Fdo

Reputation: 514

You simply put it in to an iterator.

    Iterator<Tile> tileIterator= tiles.iterator();
    while (tileIterator.hasNext()) {
        System.out.println(tileIterator.next());
    }

Edit

Change your

    List<String> tiles = new ArrayList<String> 

to

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

Then add the "tiles" items to this list. Then use below code

   Iterator<Tile> tileIterator = tiles.iterator();

    Tile t;
    while (tileIterator.hasNext()) {
        t = tileIterator.next();
        System.out.println(t.getColor().toString());
        t.setColor(your_color);
        System.out.println(t.getColor().toString());
    }

Note

Once you get the tile object to t you can use any method in the class Tile by using the t object.

Upvotes: 1

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");
}

Upvotes: 2

Benoit Vanalderweireldt
Benoit Vanalderweireldt

Reputation: 2989

You need to implement Iterable, source, then you'll be able to use your class in a "for-each-loop".

Upvotes: 0

Related Questions