集合增强for(Collection enhancement for)

collection接口和常用方法

Collection接口遍历对象方式2-for循环增强.

增强for循环,可以代替iterator迭代器,特点:增强for就是简化版的iterator,本质一样。只能用于遍历集合或数组。

  • 基本语法
    for(元素类型 元素名:集合名或数组名){
    访问元素
    }
  • 案例演示
import java.util.ArrayList;
import java.util.Collection;

public class CollectionFor {
    public static void main(String[] args) {
        Collection col = new ArrayList();

        col.add(new Book("三国演义", "罗贯中", 10.1));
        col.add(new Book("小李飞刀", "古龙", 5.1));
        col.add(new Book("红楼梦", "曹雪芹", 34.6));

        //1.使用增强for:在collection集合
        //2.增强for,底层仍然是迭代器
        //3.增强for可以理解成就是简单版本的迭代器遍历
        for (Object book : col) {
            System.out.println("book = " + book);
        }

        //增强for,也可以直接在数组使用
        int[] nums = {1,2,3,4,5};
        for (int num : nums) {
            System.out.println("num = " + num);
        }
    }
}
————————

collection接口和常用方法

Collection interface traversal object mode 2 – for loop enhancement

Enhanced for loop can replace iterator iterator. Features: enhanced for is a simplified version of iterator, which is the same in essence. Can only be used to traverse a collection or array.

  • Basic grammar
    For (element type element name: collection name or array name){
    Access element
    }
  • Case demonstration
import java.util.ArrayList;
import java.util.Collection;

public class CollectionFor {
    public static void main(String[] args) {
        Collection col = new ArrayList();

        col.add(new Book("三国演义", "罗贯中", 10.1));
        col.add(new Book("小李飞刀", "古龙", 5.1));
        col.add(new Book("红楼梦", "曹雪芹", 34.6));

        //1.使用增强for:在collection集合
        //2.增强for,底层仍然是迭代器
        //3.增强for可以理解成就是简单版本的迭代器遍历
        for (Object book : col) {
            System.out.println("book = " + book);
        }

        //增强for,也可以直接在数组使用
        int[] nums = {1,2,3,4,5};
        for (int num : nums) {
            System.out.println("num = " + num);
        }
    }
}