2013-05-08 128 views
-1

如何迭代在另一个名为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; 
    } 
    } 

} 
+1

另外:http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html – 2013-05-08 01:36:32

回答

1

编译器希望你重复这样的名单:

for(Integer val : list) { 
    .... 
} 
4
//Compiler is flagging an error here. How do I iterate over integer values of a node ? 
for(MyList ? : list.iterator()) 

你这句法起来。从头到尾完全不正确。

由于您没有指定的MyList元素类型,它是Object,所以你与Objects,迭代所以你需要

for (Object element : list) 
0

在Java高级for循环,左侧部分为对象列表包含诸如对象或字符串。右边部分是实现Iterable Interface的列表或定制类对象。你不能在这里放置一个迭代器。