我自已想实现一个链表。 
这个链表已实现Iterable和iterator接口
但在实现toArray功能。但我失败了
package Atlight;import java.util.*;public class algorithm { public static void main(String[] args) { myList<Integer> ls = new myList<Integer>();
ls.add(1);
ls.add(45);
ls.add(3);
ls.add(4);
ls.add(21); // 测试Iterable功能
for (int i : ls) {
System.out.print(i);
} // 测试iterator功能
Iterator<Integer> iter = ls.iterator();
while (iter.hasNext()) {
System.out.print(iter.next());
iter.remove();
} // 测试toArray功能 就在这里失败了 ....
// 抛出导常classCastException
Integer[] array = ls.toArray();
Arrays.toString(array);
}
}// 定义自已的链表
class myList<T> implements Iterable<T> {
private link head;
private link tail;
private long Length; public myList() {
link head = null;
link tail = null;
long Length = 0;
} public void add(T value) {
link temp = new link(value);
if (Length == 0) {
head = temp;
tail = temp;
} else {
tail.next = temp;
tail = temp;
}
Length++;
} public Iterator<T> iterator() {
return new myListIter();
} public boolean isEmpty() {
return Length <= 0;
} public T[] toArray() {
Object[] arr = new Object[(int) Length];
link tempNode = head;
for (int i = 0; i < Length; i++) {
arr[i] = tempNode.data;
tempNode = tempNode.next;
}
return (T[]) arr;
} class link {
T data;
link next; public link(T data) {
this.data = data;
next = null;
}
} public class myListIter implements Iterator<T> {
private int IterLength;
private link currentNode;
private link priorNode;
private link priorPriorNode; public myListIter() {
IterLength = 0;
currentNode = myList.this.head;
priorNode = null;
priorPriorNode = null;
} public boolean hasNext() {
return IterLength < myList.this.Length;
} public T next() {
priorPriorNode = priorNode;
priorNode = currentNode;
T value = currentNode.data;
currentNode = currentNode.next;
IterLength++;
return value;
} public void remove() {
assert currentNode != null;
if (priorPriorNode == null)
priorPriorNode = myList.this.head;
priorPriorNode.next = currentNode;
IterLength--;
Length--;
} }
}