1.

What Are The Other Methods To Iterate Over A List?

Answer»

The other methods iterate over a list in two different WAYS:

  •  Using iterator
  • Using for-each LOOP

List<String> strList = new ArrayList<>();

//using for-each loop

for(String OBJ : strList){

System.out.println(obj);

}

//using iterator

Iterator<String> it = strList.iterator();

while(it.hasNext()){

String obj = it.next();

System.out.println(obj);

}

Using iterator is more thread-safe because it provides sure that if underlying list elements are CHANGED it will throw ConcurrentModificationException.

The other methods iterate over a list in two different ways:

List<String> strList = new ArrayList<>();

//using for-each loop

for(String obj : strList){

System.out.println(obj);

}

//using iterator

Iterator<String> it = strList.iterator();

while(it.hasNext()){

String obj = it.next();

System.out.println(obj);

}

Using iterator is more thread-safe because it provides sure that if underlying list elements are changed it will throw ConcurrentModificationException.



Discussion

No Comment Found