2019年1月25日-自定义实现迭代器功能

简易迭代器原理:

package cn.liu.tree3;
/**
 * 简化迭代器原理
 * hasNext
 * next
 * @author Administrator
 *
 */

public class MyArrayList {
	private String[] elem= {"a","b","c","d","e","f","g"};
	private int size=elem.length;
	
	
	private int cursor=-1;
	/**
	 * 判断是否存在下一个元素
	 * @return
	 */
	private boolean hasNext() {
		return cursor+1<size;
	}
	/**
	 * 获取下一个元素
	 */
	private String next() {
		cursor++;//移动一次
		return elem[cursor];
	}
	/**
	 * 删除元素
	 */
	private void remove() {
		
	}
	
	public static void main(String[] args) {
		MyArrayList list =new MyArrayList();
		while(list.hasNext()) {
			System.out.println(list.next());
		}
		 
		list=new MyArrayList();
		while(list.hasNext()) {
			System.out.println(list.next());
		}
	}

}

加入接口提供方法:

package cn.liu.tree3;
/**
 * 简化迭代器原理 加入接口 提供方法
 * hasNext
 * next
 * @author Administrator
 *
 */

import java.util.Iterator;

public class MyArrayList2 {
	private String[] elem= {"a","b","c","d","e","f","g"};
	private int size=elem.length;
	
	private class MyIt implements Iterator<String>{
		private int cursor=-1;
		/**
		 * 判断是否存在下一个元素
		 * @return
		 */
		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) {
		MyArrayList2 list =new MyArrayList2();
		Iterator<String> it=list.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	
		it=list.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}

}


完善版:

package cn.liu.tree3;

import java.util.Iterator;

public class MyArrayList3 implements java.lang.Iterable<String>{
	private String[] elem= {"a","b","c","d","e","f","g"};
	private int size=elem.length;
	
	/**
	 * 匿名内部类
	 * @return
	 */	
	public Iterator<String> iterator(){
		  return new Iterator<String>(){
				private int cursor=-1;
				/**
				 * 判断是否存在下一个元素
				 * @return
				 */
				public boolean hasNext() {
					return cursor+1<size;
				}
				/**
				 * 获取下一个元素
				 */
				public String next() {
					cursor++;//移动一次
					return elem[cursor];
				}
				/**
				 * 删除元素
				 */
				public void remove() {
					
				}
		  };
	}
	
		public static void main(String[] args) {
			MyArrayList3 list=new MyArrayList3();
			Iterator<String> it=list.iterator();
			while(it.hasNext()) {
				System.out.println(it.next());
				it.remove();//删除元素
			}
			
			it=list.iterator();
			while(it.hasNext()) {
				System.out.println(it.next());
			}
			System.out.println("增强for,必须实现java.lang.Iterable接口,重写iterator方法");
			for(String temp:list) {
				System.out.println(temp);
			}
		
	
		  }
	
}

 

猜你喜欢

转载自blog.csdn.net/qq_44370562/article/details/86650275
0条评论
添加一条新回复
  
今日推荐