java 如何从 TreeSet 打印对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10572706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print objects from a TreeSet
提问by kwoebber
I want to print the instance variables of the objects I stored in my TreeSet.
我想打印存储在 TreeSet 中的对象的实例变量。
So given an Object with three instance variables, I want to iterate over the Objects in my TreeSet and print their ivars but:
因此,给定一个具有三个实例变量的对象,我想遍历 TreeSet 中的对象并打印它们的 ivars,但是:
while ( iter.hasNext() )
{
System.out.println( iter.next().getIvar1 );
System.out.println( iter.next().getIvar2 );
}
gets me the ivar1 of the first object and the ivar2 of the second object. And with all my searching I found no way of printing all the ivars of one object before moving the iterator to the next object like:
让我得到第一个对象的 ivar1 和第二个对象的 ivar2。通过我的所有搜索,我发现无法在将迭代器移动到下一个对象之前打印一个对象的所有变量,例如:
while ( iter.hasNext() )
{
System.out.println( iter.hasNext().getIvar1() );
System.out.println( iter.getIvar2 );
System.out.println( iter.getIvar3 );
System.out.println( iter.hasNext().getIvar1() );
....
}
Any ideas on how to implement that?
关于如何实施的任何想法?
Thanks in advance! =)
提前致谢!=)
回答by óscar López
Use an enhanced for loop:
使用增强的 for 循环:
for (Element element : set) {
System.out.println(element.getIvar1());
System.out.println(element.getIvar2());
}
Internally, it's just an iterator - but it saves you the trouble of manually calling next()
and hasNext()
.
在内部,它只是一个迭代器——但它省去了手动调用next()
和的麻烦hasNext()
。
回答by Matt Ball
Don't keep calling iter.next()
inside the loop. Only call it once. Every time you call Iterator.next()
, it advances the iterator to the next element in the iteration.
不要iter.next()
在循环内继续调用。只调用一次。每次调用时Iterator.next()
,它都会将迭代器推进到迭代中的下一个元素。
while ( iter.hasNext() )
{
Foo element = iter.next();
System.out.println( element.getIvar1 );
System.out.println( element.getIvar2 );
}