java学习

java学习

 

设计模式之Iterator

public interface Iterator {
Object next();
boolean hasNext();
}
public interface Collection {
void add(Object data);
int size();
Iterator iterator();
}
//集合
public class MyArrayList implements Collection{
private Object[] array = new Object[10];
private int index=0;//数值当前可以放值的下标
public void add( Object obj){
if(index==array.length){
Object[] newArray = new Object[array.length*2];
System.arraycopy(array, 0, newArray, 0, index);
array=newArray;
}
array[index]=obj;
index++;
}
public int size(){
return index;
}
@Override
public Iterator iterator() {
return new Aaa();
}
private class Aaa implements Iterator{
private int c=0;
@Override
public boolean hasNext() {
if(c<index){
return true;
}else{
return false;
}
}
@Override
public Object next() {
Object object = array[c];
c++;
return object;
}
}
public static void main(String[] args) {
MyArrayList arr = new MyArrayList();
for (int i = 0; i < 20; i++) {
arr.add(new Object());
}
System.out.println(arr.size());
Iterator iterator = arr.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
//链表
public class MyNode {
private Object data;
private MyNode nextNode;
public MyNode(Object data,MyNode nextNode){
this.data=data;
this.nextNode=nextNode;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public MyNode getNextNode() {
return nextNode;
}
public void setNextNode(MyNode nextNode) {
this.nextNode = nextNode;
}
}
public class MyLinkTable implements Collection{
private MyNode head;
private MyNode tail;
private int size = 0;
public void add(Object data) {
MyNode n = new MyNode(data, null);
if (head == null) {
head = n;
tail = n;
}
tail.setNextNode(n);
tail = n;
size++;
}
public int size() {
return size;
}
public MyNode getHead() {
return head;
}
public void setHead(MyNode head) {
this.head = head;
}
public MyNode getTail() {
return tail;
}
public void setTail(MyNode tail) {
this.tail = tail;
}
@Override
public Iterator iterator() {
return new Aaa();
}
private class Aaa implements Iterator{
private int c=0;
MyNode node=null;
@Override
public boolean hasNext() {
for (int i = 0; i <=c; i++) {
if(i==0){
node = head;
}else{
node = node.getNextNode();
}
}
if(node==null){
return false;
}else{
return true;
}
}
@Override
public Object next() {
for (int i = 0; i <=c; i++) {
if(i==0){
node = head;
}else{
node = node.getNextNode();
}
}
c++;
return node;
}
}
public static void main(String[] args) {
MyLinkTable node = new MyLinkTable();
node.add(1);
node.add(2);
node.add(3);
Iterator iterator = node.iterator();
while(iterator.hasNext()){
MyNode node1= (MyNode) iterator.next();
System.out.println(node1.getData());
}
}
}

posted on 2017-09-12 15:54 杨军威 阅读(111) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜