4

program:

public class SortedSet1 {

  public static void main(String[] args) {  

    List ac= new ArrayList();

    c.add(ac);
    ac.add(0,"hai");
    ac.add(1,"hw");
    ac.add(2,"ai"); 
    ac.add(3,"hi"); 
    ac.add("hai");

    Collections.sort(ac);

    Iterator it=ac.iterator();

    k=0;

    while(it.hasNext()) {    
      System.out.println(""+ac.get(k));
      k++;     
    }
  }
}

output: ai hai hi hw hai

how it execute 5 times?? while come to hai no next element present so condition false. But how it executed.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
Vinoth Kumar
  • 3,243
  • 7
  • 24
  • 13
  • 1
    The real question is, How do I use an Iterator and why am I getting an indexOutOfBounds-exception. – Cid54 Sep 03 '10 at 12:08

3 Answers3

16

Your loop above iterates through the list using an index. it.hasNext() returns true until it reaches the end of the list. Since you don't call it.next() within your loop to advance the iterator, it.hasNext() keeps returning true, and your loop rolls on. Until, that is, k gets to be 5, at which point an IndexOutOfBoundsException is thrown, which exits the loop.

The proper idiom using an iterator would be

while(it.hasNext()){
    System.out.println(it.next());
}

or using an index

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

However since Java5, the preferred way is using the foreach loop (and generics):

List<String> ac= new ArrayList<String>();
...
for(String elem : ac){
    System.out.println(elem);
}
Péter Török
  • 114,404
  • 31
  • 268
  • 329
2

the point is ac.get(k) doesn't consume any element of the iterator at the contrary of it.next()

Xavier Combelle
  • 10,968
  • 5
  • 28
  • 52
0

That loop will never terminate. it.hasNext does not advance the iterator. You have to call it.next() to advance it. The loop probably terminates because k becomes 5 at which point the Arraylist with throw a bounds exception.

The correct form of iterating a list (containing strings) is either:

Iterator it = ac.iterator();
while (it.hasNext) {
  System.out.println((String) it.next());
}

Or if the list is typed, e.g. ArrayList

for (String s : ac) {
  System.out.println((String) s);
}

Or if you absolutely know this is an array list and need speed over terseness:

for (int i = 0; i < ac.size(); i++) {
  System.out.println(ac.get(i));
}
locka
  • 5,809
  • 3
  • 33
  • 38