When I did a source review, I was told, "I thought the extended for statement was for List only!", So I'll write here again, "That's not the case."
Both methods produce the same result.
List<String> strList = new ArrayList<String>(); //The assignment process to the list element is omitted.
//Loop the list with a normal for statement.
for ( int i = 0 ; i < strList.size() ; i++) {
System.out.println(strList.get(i));
}
//Loop the list with an extended for statement.
for (String string : strList) {
System.out.println(string);
}
The same result is output here as well.
String[] strArray = new String[5]; //Assignment processing to array elements is omitted.
//Loop the array with a normal for statement.
for ( int i = 0 ; i < strArray.length ; i++) {
System.out.println(strArray[i]);
}
//Loop the array with an extended for statement.
for (String string : strArray) {
System.out.println(string);
}
I use it properly depending on whether I want the value of index.
--When you want the value of index: point_right: Ordinary for loop. --You don't need the index value, so when you just want to go around: point_right: Extended for statement.
Personally, I think the source is hard to read when using index. When a long variable name comes out in business, it is usually taken out to a variable once like `` `strList.get (i) ``` in consideration of readability. At the sample level above, it doesn't matter if you extract it to a variable once, but (I) sometimes feel a little annoyed when it comes to business.
--List loops can be written with ordinary for statements or extended for statements. --The extended for statement can be used for arrays, and ordinary for statements are OK: ok_hand: -(Personally) I use it properly depending on whether I want the index value.
Recommended Posts