Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print objects from a TreeSet

I want to print the instance variables of the objects I stored in my TreeSet.

So given an Object with three instance variables, I want to iterate over the Objects in my TreeSet and print their ivars but:

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:

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! =)

like image 885
kwoebber Avatar asked May 13 '12 14:05

kwoebber


2 Answers

Use an enhanced for loop:

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().

like image 75
Óscar López Avatar answered Sep 23 '22 03:09

Óscar López


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.

while ( iter.hasNext() )
{
    Foo element = iter.next();
  System.out.println( element.getIvar1 );
  System.out.println( element.getIvar2 );
}
like image 34
Matt Ball Avatar answered Sep 22 '22 03:09

Matt Ball