foreach not applicable to expression type

前端 未结 3 1417
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-11 18:39

what does this error mean? and how do i solve it?

foreach not applicable to expression type.

im am trying to write a method find(). that find a string in a l

相关标签:
3条回答
  • 2021-01-11 19:28

    Without code this is just a grasp at straws.

    If you're trying to write your own list-find method, it would be like this

    <E> boolean contains(E e, List<E> list) {
    
        for(E v : list) if(v.equals(e)) return true;
        return false;
    }
    
    0 讨论(0)
  • 2021-01-11 19:33

    Make sure your for-construct looks like this

        LinkedList<String> stringList = new  LinkedList<String>();
        //populate stringList
    
        for(String item : stringList)
        {
            // do something with item
        }
    
    0 讨论(0)
  • 2021-01-11 19:42

    Are you using an iterator instead of an array?

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

    You cannot just pass an Iterator into the enhanced for-loop. The 2nd line of the following will generate a compilation error:

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

    The error:

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

    I just saw that you have your own Stack class. You do realize that there is one already in the SDK, right? http://download.oracle.com/javase/6/docs/api/java/util/Stack.html You need to implement Iterable interface in order to use this form of the for loop: http://download.oracle.com/javase/6/docs/api/java/lang/Iterable.html

    0 讨论(0)
提交回复
热议问题