In Java, you implement a class that can use the Foreach Loop iterable,iterator

Source: Internet
Author: User
Tags iterable

To implement a class that can be used with a foreach loop, you must implement Iterable, which overrides a Iterator method, which returns a iterator<e> interface.

The code is as follows:

public class Itertest   implements Iterable<string> {
Stores the contents of the array private object[] Obj=new object[1];//record the number of elements added to the private int size;
Records the current element's subscript private int current=0;//add element public void Add (String str) {
Determine if the array is full if it is full of expanded array if (size==obj.length) {//expanded array to a new length obj=arrays.copyof (obj, obj.length+obj.length<<1);} Obj[size++]=str;}
Overriding the Iterator method public iterator<string> Iterator () {defines inner classes that implement the Iterator class "ITER implements Iterator<string >{@Overridepublic Boolean Hasnext () {//Determines whether the current pointer is less than the actual size if (current<size) {return true;} return false;} @Overridepublic String Next () {//returns the current element and moves the current subscript forward to return obj[current++].tostring ();} @Overridepublic void Remove () {//TODO auto-generated Method stub}}//Returns the custom Iteraror subclass return new ITER ();}}

  

In Java, you implement a class that can use the Foreach Loop iterable,iterator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.