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

How to use iterable in java

WBOY
Release: 2023-04-24 15:13:14
forward
2368 people have browsed it

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());
        }
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template