在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 中容器及容器遍历有更深的理解。