如何迭代在另一个名为Binary Tree的类中使用的linkedList节点。在一个侧面说明,任何建议使其更多的面向对象,而不是宣布公共内部类?为什么编译器说我只能在MyList实现迭代时迭代迭代一个迭代的实例?
public class BinaryTree
{
Node root;
class Node
{
Integer value;
Node left;
Node right;
Node(int value)
{
this.value = value;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyList list = new MyList();
list.create(8);
list.create(7);
list.create(6);
list.create(5);
list.create(4);
list.create(3);
list.create(2);
list.create(1);
//Compiler is flagging an error here. How do I iterate over integer values of a node ?
for(MyList ? : list.iterator())
{
System.out.println(node.getVal());
System.out.println("-->");
}
}
// MYLIST类
package com.linkedlist;
import java.util.Iterator;
@SuppressWarnings("rawtypes")
public class MyList implements Iterable{
private Node head;
public Node getHead()
{
return head;
}
@Override
public Iterator iterator() {
return new ListIterator();
}
public class Node
{
Integer val;
Node next;
Node(int data)
{
this.val = data;
}
public Integer getVal()
{
return this.val;
}
public Node getNext()
{
return this.next;
}
}
public Node create(int data)
{
if(head==null)
return new Node(data);
else
{
head.next = new Node(data);
return head;
}
}
private class ListIterator implements Iterator
{
private Node current = head;
public boolean hasNext() { return current != null; }
public void remove() { /* not supported */ }
public Integer next()
{
Integer val = current.val;
current = current.next;
return val;
}
}
}
另外:http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html – 2013-05-08 01:36:32