foreach不适用于表达类型

时间:2011-04-25 21:11:51

标签: java

这个错误是什么意思?我该如何解决呢?

foreach不适用于表达类型。

我正在尝试编写一个方法find()。在链表中找到一个字符串

public class Stack<Item>
{
    private Node first;

    private class Node
    {
        Item item;
        Node next;
    }

    public boolean isEmpty()
    {
        return ( first == null );
    }

    public void push( Item item )
    {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
    }

    public Item pop()
    {
        Item item = first.item;
        first = first.next;
        return item;
    }
}


public find
{
    public static void main( String[] args )
    {
    Stack<String> s = new Stack<String>();

    String key = "be";

    while( !StdIn.isEmpty() )
        {
        String item = StdIn.readString();
        if( !item.equals("-") )
            s.push( item );
        else 
            StdOut.print( s.pop() + " " );
        }

    s.find1( s, key );
     }

     public boolean find1( Stack<String> s, String key )
    {
    for( String item : s )
        {
        if( item.equals( key ) )
            return true;
        }
    return false;
    }
}

这是我的所有代码

3 个答案:

答案 0 :(得分:11)

您使用的是迭代器而不是数组吗?

http://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

  

你不能只将Iterator传递给增强的for循环。以下第二行将生成编译错误:

    Iterator<Penguin> it = colony.getPenguins();
    for (Penguin p : it) {
     

错误:

    BadColony.java:36: foreach not applicable to expression type
        for (Penguin p : it) {

我刚看到你有自己的Stack类。您确实意识到SDK中已有一个,对吧? http://download.oracle.com/javase/6/docs/api/java/util/Stack.html 您需要实施Iterable界面才能使用此for循环形式:http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

答案 1 :(得分:2)

确保你的for-construct看起来像这样

    LinkedList<String> stringList = new  LinkedList<String>();
    //populate stringList

    for(String item : stringList)
    {
        // do something with item
    }

答案 2 :(得分:0)

没有代码,这只是对稻草的把握。

如果您正在尝试编写自己的list-find方法,那就像这样

<E> boolean contains(E e, List<E> list) {

    for(E v : list) if(v.equals(e)) return true;
    return false;
}