话不多说直接上代码:
package com.moshi.iterator2;
public interface List<R> {
boolean add(R r);
boolean isEempty();
int getSize();
public Iterator<R> iterator();
}
package com.moshi.iterator2;
public class ArrayList<E> implements List<E> {
private Object[] o=new Object[10];
int index=0;
@Override
public boolean add(E r) {
if(index==o.length){
Object[] newo=new Object[o.length*2];
System.arraycopy(o, 0, newo, 0, o.length);
o=newo;
}
o[index]=r;
index++;
return true;
}
@Override
public boolean isEempty() {
if(index==0)return true;
return false;
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return index;
}
@Override
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return new Arrayiterator<E>();
}
@SuppressWarnings("hiding")
private class Arrayiterator<E> implements Iterator<E>{
private int currentIndex = 0;
@Override
public boolean hasNext() {
if(currentIndex >= index) return false;
else return true;
}
@SuppressWarnings("unchecked")
@Override
public E next() {
E ob = (E) o[currentIndex];
currentIndex ++;
return ob;
}
}
}
package com.moshi.iterator2;
public class LinkedList<R> implements List<R> {
Node head = null;
Node tail = null;
int size = 0;
public boolean add(R o) {
Node n = new Node(o, null);
if(head == null) {
head = n;
tail = n;
}
tail.setNext(n);
tail = n;
size ++;
return true;
}
public Iterator<R> iterator() {
return new LinkedIterator<R>();
}
@Override
public boolean isEempty() {
if(size==0)return true;
return false;
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return size;
}
@SuppressWarnings("hiding")
private class LinkedIterator<R> implements Iterator<R>{
private Node currentNode=head;
@SuppressWarnings("unchecked")
@Override
public R next() {
R a=(R) currentNode.getData();
currentNode=currentNode.getNext();
return a ;
}
@Override
public boolean hasNext() {
if(currentNode==null){
return false;
}
return true;
}
}
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
package com.moshi.iterator2;
public class A {
private String name;
private int age;
public A(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.moshi.iterator2;
public class Client {
public static void main(String[] args) {
List<A> l=new ArrayList<A>();
//List<A> l=new LinkedList<>();
for(int i=0;i<15;i++){
A a=new A("xiao",i);
l.add(a);
}
System.out.println(l.getSize());
Iterator<A> ita= l.iterator();
while(ita.hasNext()){
A a= ita.next();
System.out.println(a.getAge());
}
}
}