由链表实现的容器

在java中用链表实现一个容器,将对象添加到容器中并打遍历该容器

首先,定义一个类 Node 作为链表的一个结点,我们知道每个节点都有两部分内容:

1,该结点保存的内容 

2,指向下一个结点的指针

package com.dp.iterator;

public class Node {
	private Object data;
	private Node next;

	public Node(Object data, Node next) {
		super();
		this.data = data;
		this.next = next;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public Node getNext() {
		return next;
	}
	public void setNext(Node next) {
		this.next = next;
	}

}

定义一个 LinkedList 链表类。该类实现了 Collection 接口

package com.dp.iterator;

//链表实现的容器
public class LinkedList implements Collection{
	Node head = null;
	Node tail = null;
	int size = 0;
	
	public void add(Object o){
		Node n = new Node(o,null);
		if(head == null){
			head = n;
			tail = n;
		}
		tail.setNext(n);
		tail = n;
		size ++;
		
	}
	
	public int size(){
		return size;
	}

	@Override
	public Iterator iterator() {
		// TODO Auto-generated method stub
		return new LinkedListIterator();
	}
	
	public class LinkedListIterator implements Iterator{
		private Node currentNode = null;
		
		@Override
		public boolean hasNext() {
			// TODO Auto-generated method stub
			if(currentNode == tail){
				return false;
			} else {
				return true;
			}
		}

		@Override
		public Object next() {
			// TODO Auto-generated method stub
			if(currentNode == null){
				currentNode = head;
			} else {
				//System.out.println("help");
				currentNode = currentNode.getNext();				
			}

			return currentNode.getData();
		}
		
	}
}

Collection 接口:

package com.dp.iterator;

public interface Collection {
	void add(Object o);
	int size();
	Iterator iterator();
}

而 Collection 接口中又引用了 Iterator 接口,而该 Iterator 接口是在 LinkedList 类中能过内部类来实现的。

package com.dp.iterator;

public interface Iterator {
	boolean hasNext();
	Object next();
}


辅助类 Cat.java

package com.dp.iterator;

public class Cat {
	public Cat(int id) {
	
		this.id = id;
	}

	private int id;
	
	public String toString(){
		return "Cat " + id;
	}
}


测试类 Test.java

package com.dp.iterator;
import com.dp.iterator.LinkedList;
import com.dp.iterator.ArrayList;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//ArrayList arrayList = new ArrayList();
		//LinkedList arrayList = new LinkedList();
		Collection c = new LinkedList();
		
		for(int i = 0; i < 15; i ++){
			c.add(new Cat(i));
		}
		System.out.println("size" + c.size());
		
		Iterator it = c.iterator();
		while(it.hasNext()){
			Object o = it.next();
			System.out.println(" " + o);
		}
	}

}

该文主要是提供了一种模拟 JDK 容器及迭代子的一种方法。通过这个实现可以加深对 JDK 中容器及容器遍历有更深的理解。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值