0

Being new to Java, the following code confuses me. I'm trying to do a simple loop based on a list.

List memberships = getMembership(username);
for( Iterator<Integer> single = memberships.iterator(); single.hasNext(); ) 
{
    System.out.println(print_the_current_string_in_list);
} 

I have the following questions:

  • The loop never stops with the above, even though I only have three items in the list. Why is this?
  • How can I output the current string in the list?

5 Answers 5

5

Hopefully your List if of type String and not Integer so it should be

List<String> memberships = getMembership(username);

There are multiple ways to loop over the data for example:

for(String single : memberships) {
    System.out.println(single);
}

Another way:

for(int i = 0; i < memberships.size(); i++) {
   System.out.println(memberships.get(i));
}

Using the Iterator

for(Iterator<String> iterator = membership.iterator(); iterator.hasNext();) {
    System.out.println(iterator.next());
}

Instead of using a for loop you may use an Iterator with a while loop

Iterator<String> iterator = membership.iterator();
while(iterator.hasNext()) {
    System.out.println(iterator.next());
}
Sign up to request clarification or add additional context in comments.

1 Comment

This seemed to do the trick! I had actually tried out the for(String single : memberships) but this wasnt working because i had not specified the type in the List delaration of memberships.
2

Try an advanced for loop, like so:

for(String membership : memberships)
    System.out.println(membership);

Comments

2

You can use the foreach statement, which uses the iterator that the list has already implemented. And you should also specify the type of the elements that the list will contain in the List declaration, like this:

List<String> memberships = getMembership(username);
for( String m : memberships ) 
{
    System.out.println(m);
}

Comments

1

You need to actually iterate over the members with next() method from Iterator:

for (Iterator<Integer> single = memberships.iterator (); single.hasNext (); ) {
  Integer next = single.next ();
  System.out.println (next);
}

Also, you can use the new for each construct:

for (Integer current : memberships)
  System.out.println (current);

Comments

1

You haven't iterated through the list.Use next() method.Thats why its going into an infinite loop.

 for( Iterator<Integer> single = memberships.iterator(); single.hasNext();{
        System.out.println( single.next());
    } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.