Java - Collection - iterator 方法

By sunwc 2023-03-28 Java
/**
 * @author sunwc
 * @create 2023-03-28 上午 09:56
 */
public class CollectionTest {


    @Test
    public void testCollection() {

        Collection collection = new ArrayList<>();

        Person person = new Person("Jerry", 20);
        collection.add(person);
        collection.add(123);
        collection.add(456);
        collection.add(false);
        collection.add(new String("Tom"));

        // 每次集合調用iterator()時都會得到一個全新的 迭代器
        Iterator iterator = collection.iterator(); 

        while (iterator.hasNext()) {

            // 走到next()後,指針才下移;所以如果要調remove()的話,要先調next()
            Object next = iterator.next(); 

            // 刪除集合中的Tom
            if ("Tom".equals(next)) {
                iterator.remove(); // 迭代的過程進行移除元素
            }
            System.out.println(next);
        }

        System.out.println(collection.contains(new String("Tom"))); // false

    }
}

class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Person{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

}

JDK 5.0 新增 集合Collection 的增強for迴圈特性

練習題


String[] arr = new String[]{"MM","MM","MM"};

// 方式一、直接改變arr[index]的元素值
for(int i = 0; i < arr.length; i++) {
    arr[i] = "GG";
}

for(int i = 0; i < arr.length; i++) {
    System.out.print(arr[i]+"\t"); // GG GG GG
}

String[] arr = new String[]{"MM","MM","MM"};

// 方式二、從arr取出值後,將值複製一份給變數str
for(String str: arr) {
    str = "GG";
}

for(int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]+"\t"); // MM MM MM
}