Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to use for to traverse collections in Java?
How to use for to traverse collections in Java?
The enhanced for loop is the same as the ordinary for loop.

The advantages of the enhanced for loop are mainly embodied in the collection, just give an example.

Such as the traversal of a set.

General iterative traversal:

Set< string & gtset = new HashSet & lt string & gt ();

Iterator & lt string & gtit = set.iterator ();

while (it.hasNext()) {

string str = it . next();

system . out . println(str);

}

For loop traversal:

for (String str : set) {

system . out . println(str);

}

Is it simpler?

The advantage also lies in generics. If the object is stored in a collection.

Set< object & gt set = new hashset & lt object & gt ();

For loop traversal:

For (object object: set) (

if(obj instanceof Integer){

int aa =(Integer)obj;

}else if(obj instanceof String){

String aa = (string) obj

}

........

}

The only drawback is that the collection itself cannot be manipulated when traversing the collection.

for (String str : set) {

set . remove(str); //Error!

}