Java 问题遍历类的树形图集合
我尝试使用以下方法迭代 Tile() 类的 Treemap:
Map map = new TreeMap();
Iterator itr = world.map.values().iterator();
while(itr.hasNext()){
Tile t = ???;
System.out.print(t.xCord+","+t.yCord+","+t.zCord);
}
如何在迭代器中获取对象 Tile 的实例?或者如果有更好的方法可以做到这一点,请告诉我。
我试过用谷歌搜索这个,但我总是最终寻找迭代纯数据的方法,比如字符串等,而不是类的实例化......
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'...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
字符串不是 Java 中的纯数据,它们是对象,因此是相同的:
或更好:
甚至更好:
ps
Key
是您正在使用的关键对象的类Strings aren't pure data in Java, they are objects, so is the same:
Or better:
or even better:
p.s
Key
is the class of the key objects you're using但请注意,使用迭代器(尤其是原始集合)是一种非常过时的 Java 编写方式。更好的是使用类型化集合和增强的 for 循环:
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:
itr.next()
给出下一个元素的实例,如 javadocs。请注意,由于您的地图是原始类型,因此您需要进行强制转换:Tile t = (Tile)itr.next();
,但它不是类型安全的。更好的解决方案是使用泛型,如 @Simone 建议的那样
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
However, you'd also have to cast the tile unless you gave the type with generics:
Otherwise the iterator values will have to be cast - i.e. you'd have to correct your example (and the lines above) to
在循环中,使用
itr.next()
从Iterator
检索下一个Tile
对象。目前,这将返回一个Object
,因为您使用的是原始类型的TreeMap
。而是使用TreeMap
,以便值迭代器将是Iterator
。Within the loop, use
itr.next()
to retrieve the nextTile
object from theIterator
. Currently this will return anObject
, since you are using a raw-typedTreeMap
. Instead useTreeMap<Key, Tile>
, so that the values iterator will be anIterator<Tile>
.Tile t = (Tile) itr.next()
这将为您提供该类的下一个实例,并将迭代器移动到下一个实例。
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.