本文主要是介绍泛型第四课,自定义实现迭代器、深入迭代器、迭代器原理,面向对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package com.pkushutong.genericity4;import java.util.Iterator;/*** 简化迭代器原理* @author dell**/
public class Array2 implements java.lang.Iterable<String>{private String[] elem = {"a","b","c","d","e","f","g"};private int size = elem.length;public class MyIt implements Iterator<String>{//游标private int cursor = -1;//判断是否存在下一个元素public boolean hasNext(){return cursor + 1< size;}//获取下一个元素public String next(){cursor++;return elem[cursor];}//删除元素public void remove(){}}public Iterator<String> iterator(){return new MyIt();}public static void main(String[] args) {Array2 list = new Array2();Iterator it = list.iterator();while(it.hasNext()){String str = (String) it.next();System.out.println(str);}//增强for循环,必须实现java.lang.Iterable接口,重写iterator方法for (String st : list) {System.out.println(st);}}
}
这篇关于泛型第四课,自定义实现迭代器、深入迭代器、迭代器原理,面向对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!