Home  >  Article  >  Java  >  How to use iterable in java

How to use iterable in java

WBOY
WBOYforward
2023-04-24 15:13:142337browse

1. Concept

is one of the top interfaces of Java collection. The Collection interface inherits Iterable, so all subclasses of Collection also implement the Iterable interface.

The core method of this interface is: Iterator< T > iterator(); This method returns an Iterator class for iterating elements.

2. Usage Notes

(1) Objects that implement this interface are allowed to use the for-each loop syntax.

(2) Since the Collection interface inherits the Iterable interface, all implementation classes that implement Collection implement the Iterable interface .

3. The difference between Iterator and Iterable

The Iterator interface provides a unified way to traverse collection elements. When using the Iterator object, you don't need to worry about the specific type and internal implementation of the specific collection object. You can traverse the collection by uniformly using the interface methods of the Iterator object.

Iterable interface is designed for foreach loop. The Iterable interface indicates that a collection can return an Iterator object. Finally, use Iterator for traversal.

4. Example

The collection object gets a new iterator object every time it calls the iterator() method. The default cursor is before the first element of the collection. .

public class RunoobTest {
    public static void main(String[] args) {
 
        // 创建集合
        ArrayList<String> sites = new ArrayList<String>();
        sites.add("Google");
        sites.add("Runoob");
        sites.add("Taobao");
        sites.add("Zhihu");
 
        // 获取迭代器
        Iterator<String> it = sites.iterator();
 
        // 输出集合中的所有元素
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

The above is the detailed content of How to use iterable in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete