0

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

1
  • How can tiles include all the tiles if it is List<String> tiles = new ArrayList<String>(). Shouldn't it be List<Tile> tiles = new ArrayList<Tile>();? If you change tiles to be that you can simple do for(Tile tile: files) { tile.setColor(color); } or whatever you have to do. Commented Mar 24, 2016 at 4:33

3 Answers 3

2

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");
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

What If I want to access at the same setColor() method from tile, how do I use it with the iterator? tileIterator.setColor() wouldnt work
@evgeni-mironov: Try the edit section and see. You should add you tiles objects to the List using tiles.add(your_tile_object)
the Tiles was actually already a type <Tile>, my bad about that, your way works. Thanks a lot for the help
0

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

1 Comment

I thought about iterator, but I how do i access setColor() with iterator , because I need to set a tile to a color

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.