How hasnext () works in a collection in java

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++;     
    }
  }
}

Yield: Artificial Intelligence Hi Hi HW Hai

How is it performed 5 times? while they come to hai there is no next element, so the condition is false. But how is this done.

+3
source share
3 answers

. it.hasNext() true , it . it.next() , it.hasNext() true, . , k 5, a IndexOutOfBoundsException, .

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

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

, Java5, foreach ( generics):

List<String> ac= new ArrayList<String>();
...
for(String elem : ac){
    System.out.println(elem);
}
+14

ac.get(k) .next()

+2

This cycle will never end. it.hasNext does not promote an iterator. You must call it .next () to promote it. The loop probably ends because k becomes 5, at which point the Arraylist discards the exception of boundaries.

The correct form for iterating a list (containing strings):

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

Or if the list is entered, for example. Arraylist

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

Or, if you absolutely know that this is a list of arrays and you need speed compared:

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

Source: https://habr.com/ru/post/1763063/


All Articles