叫做for循环增强

    1. package fangxing;
    2. import java.util.ArrayList;
    3. import java.util.Iterator;
    4. import java.util.List;
    5. /*
    6. 集合使用Foreach
    7. */
    8. public class ForEachTest02 {
    9. public static void main(String[] args) {
    10. List<String> st = new ArrayList<>();
    11. st.add("helo");
    12. st.add("world");
    13. //使用迭代器遍历
    14. Iterator<String> it = st.iterator();
    15. while(it.hasNext()){
    16. String s = it.next();
    17. System.out.println(s);
    18. }
    19. /*
    20. 使用下标的方式
    21. */
    22. for(int i = 0;i<st.size();i++){
    23. System.out.println(st.get(i));
    24. }
    25. /*
    26. 使用foreach
    27. */
    28. for(String s :st){
    29. System.out.println(s);
    30. }
    31. }
    32. }
    1. package fangxing;
    2. /*
    3. 数组使用foreach
    4. */
    5. public class ForEachTest01 {
    6. public static void main(String[] args) {
    7. int[] arr ={1,3,5,7,9};
    8. for(int data:arr){
    9. System.out.println(data);
    10. }
    11. }
    12. }