public interface Collection {
void add(Object o);
int size();
}
----------
public class ArrayList implements Collection {
private int size=0;
Object[] os = new Object[10];
@Override
public void add(Object o) {
if(size == os.length){
Object[] newOs = new Object[os.length*2];
System.arraycopy(os, 0, newOs, 0, os.length);
os = newOs;
}
os[size] = o;
size++;
}
@Override
public int size() {
return size;
}
Iterator iterator(){
ArrayListIterator it = new ArrayListIterator();
return it;
}
class ArrayListIterator implements Iterator{
int current = 0;
@Override
public boolean hasNext() {
if(current==size)
return false;
else {
current++;///
return true;
}
}
@Override
public Object next() {
return os[current-1];
}
}
}
----------
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Thinkpad
*
*/
public class ArrayListTest {
/**
* Test method for {@link ArrayList#add(java.lang.Object)}.
*/
@Test
public void testAdd() {
String str="test---";
ArrayList al = new ArrayList();
for(int i=0;i<3;i++){
al.add(str+i);
}
Iterator it = al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
----------
public interface Iterator {
boolean hasNext();
Object next();
}
----------
public class LinkedList implements Collection {
private int size = 0;
Node head = new Node();
Node tail = head;
@Override
public void add(Object o) {
Node n = new Node();
tail.setData(o);
tail.setNode(n);
tail = n;
size++;
}
@Override
public int size() {
return size;
}
Iterator iterator() {
return new LinkedListIterator();
}
private class Node {
Object data;
Node node;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
}
class LinkedListIterator implements Iterator {
Node temp = head;
Node data = temp;
@Override
public boolean hasNext() {
if (temp.node == null)
return false;
else {
data = temp;
temp = temp.node;
return true;
}
}
@Override
public Object next() {
return data.data;
}
}
}
----------
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Thinkpad
*
*/
public class LinkedListTest {
/**
* Test method for {@link LinkedList#add(java.lang.Object)}.
*/
@Test
public void testAdd() {
LinkedList ll = new LinkedList();
ll.add(new String("ni hao a!"));
ll.add(new String("wo ye hao a!"));
Iterator it = ll.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
Iterator
最新推荐文章于 2023-02-02 21:28:19 发布