Java Iterator iterator


Iterator

  • Iterator is an interface, such as is necessary to rely on the method defined in the interface Collection: public Iterator <> iterator ();

1. Definition Interface

Types of method Explanation
boolean hasNext() It used to determine whether there is a next element in the collection can iterate
E next() A return element for the next iteration, and rearward movement of a pointer
void remove() Next time you use the delete () call to the elements, you must use next, then use romove, if you first remove method will use an IllegalStateException

2. Java Examples

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class test {
    public static void main(String[] args) {
        Collection<String> coll = new ArrayList();
        coll.add("apple");
        coll.add("banana");
        System.out.println(coll.size());
        ArrayList array = new ArrayList();
        array.add("cat");
        array.add("dog");
        if (!array.isEmpty()) {
            coll.addAll(array);
        }
        System.out.println(coll.size());
        Iterator<String> it = coll.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();
        if (coll.contains("Cat")) {
            System.out.print("coll has cat.");
        }
        coll.removeAll(array);
        it = coll.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();
        Object[] str = coll.toArray();
        String s = "";
        System.out.print("elements in coll: ");
        for (int i = 0; i < str.length; i++) {
            s = (String) str[i];//任何对象加入集合后如果不泛化都会自动转变为Object类型,所以在取出的时候要强制类型转换
            System.out.print(s + " ");
        }
    }
}
Published 59 original articles · won praise 60 · views 1583

Guess you like

Origin blog.csdn.net/Regino/article/details/104549538
Recommended