用处:集合的遍历
先上类图
案例代码
简单实现ArrayList 和 LinkList
package com.wwj.iteartormode;
public class Main {
public static void main(String[] args) {
Collection_<String> test = new ArrayList_();
test.add("1");
test.add("2");
test.add("3");
Iteartor_ iteartor = test.iteartor();
while (iteartor.hasNext()){
System.out.println(iteartor.next());
}
Collection_<String> test2 = new LinkList_();
test2.add("4");
test2.add("5");
test2.add("6");
Iteartor_ iteartor2 = test2.iteartor();
while (iteartor2.hasNext()){
System.out.println(iteartor2.next());
}
}
}
/**
* 集合接口
*/
interface Collection_<T>{
void add(T o);
int size();
Iteartor_ iteartor();
}
/**
* 遍历器
*/
interface Iteartor_{
Boolean hasNext();
Object next();
}
/**
* 自定义ArrayList练习
*/
class ArrayList_<T> implements Collection_<T>{
Object[] objects = new Object[10];
private int index = 0;
@Override
public void add(T o){
if(index == objects.length){
Object[] newObjects = new Object[objects.length*2];
System.arraycopy(objects,0,newObjects,0,objects.length);
objects = newObjects;
}
objects[index] = o;
index++;
}
@Override
public int size(){
return this.index;
}
@Override
public Iteartor_ iteartor() {
return new ArrayListIteartor();
}
/**
* 定义自己的迭代器
*/
private class ArrayListIteartor implements Iteartor_{
private int currentIndex = 0;
@Override
public Boolean hasNext() {
if(currentIndex >= index){
return false;
}
return true;
}
@Override
public T next() {
Object object = objects[currentIndex];
currentIndex++;
return (T)object;
}
}
}
/**
* 简单实现LinkList
*/
class LinkList_<T> implements Collection_<T>{
Node head;
Node tail;
private int size = 0;
@Override
public void add(T o) {
Node n = new Node(o);
if(head == null){
head = n;
}else{
tail.next = n;
}
tail = n;
size++;
}
@Override
public int size() {
return this.size;
}
@Override
public Iteartor_ iteartor() {
return new LinkListIteartor();
}
/**
* 定义node节点
*/
protected class Node{
private T object;
Node next;
public Node(T object) {
this.object = object;
}
}
/**
* 定义自己的迭代器
*/
private class LinkListIteartor implements Iteartor_{
private int currentIndex = 0;
private Node currentNode;
@Override
public Boolean hasNext() {
if(currentIndex >= size){
return false;
}
return true;
}
@Override
public T next() {
if (currentNode == null){
currentNode = head;
}else {
currentNode = currentNode.next;
}
currentIndex++;
return currentNode.object;
}
}
}