Question

Im trying to iterate through a Treemap of the class Tile() using:

Map map = new TreeMap();

Iterator itr = world.map.values().iterator();

while(itr.hasNext()){
     Tile t = ???;
     System.out.print(t.xCord+","+t.yCord+","+t.zCord);
}

How do I get the instance of the object Tile within the iterator? Or if theres some better way of doing this, plz let me know.

I've tried googling this, but I always end up looking at ways to iterate through pure data, like strings etc, and not Instanciations of class'...

Was it helpful?

Solution

Strings aren't pure data in Java, they are objects, so is the same:

Map map = new TreeMap();

Iterator itr = world.map.values().iterator();

while(itr.hasNext()){
    Tile t = (Tile)itr.next();
    System.out.print(t.xCord+","+t.yCord+","+t.zCord);
}

Or better:

Map<Key, Tile> map = new TreeMap<Key, Tile>();

Iterator<Tile> itr = world.map.values().iterator();

while(itr.hasNext()){
    Tile t = itr.next();
    System.out.print(t.xCord+","+t.yCord+","+t.zCord);
}

or even better:

Map<Key, Tile> map = new TreeMap<Key, Tile>();

for(Tile t : map.values){
    System.out.print(t.xCord+","+t.yCord+","+t.zCord);
}

p.s Key is the class of the key objects you're using

OTHER TIPS

Tile t = (Tile) itr.next();

But note that using Iterators and especially raw collections is a very outdated way of writing Java. Much better would be using typed collections and the enhanced for loop:

Map<String, Tile> map = new TreeMap<String, Tile>();

for(Tile t : map.values()){
     System.out.print(t.xCord+","+t.yCord+","+t.zCord);
}

itr.next() gives the instance of the next element, as specified in the javadocs. Note that since your Map is of raw type, you will need a cast: Tile t = (Tile)itr.next(); but it is NOT type safe.

Even better solution is using generics as @Simone suggested

In an iterator you use

while(itr.hasNext()){
     Tile t = itr.next(); ...

However, you'd also have to cast the tile unless you gave the type with generics:

Map<Whatever,Tile> map = new TreeMap<Whatever,Tile>();
Iterator<Tile> itr = world.map.values().iterator();

Otherwise the iterator values will have to be cast - i.e. you'd have to correct your example (and the lines above) to

while(itr.hasNext()){
         Tile t = (Tile)itr.next(); ...

Within the loop, use itr.next() to retrieve the next Tile object from the Iterator. Currently this will return an Object, since you are using a raw-typed TreeMap. Instead use TreeMap<Key, Tile>, so that the values iterator will be an Iterator<Tile>.

Tile t = (Tile) itr.next()

This will give you the next instance of the class as well as move the iterator to the next instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top