开发者

What's wrong with this print-iterable method?

开发者 https://www.devze.com 2023-01-02 12:53 出处:网络
private st开发者_如何学Catic void printIterable(Iterable iterable) { // ERROR: \"Type mismatch: cannot convert from element type Object to Iterable\"
private st开发者_如何学Catic void printIterable(Iterable iterable) {

    // ERROR: "Type mismatch: cannot convert from element type Object to Iterable"
    for (Iterable i : iterable) { 
        System.out.println(i);
    }

}

What the compiler is talking about? Its an Iterable, not an Object.


You try to do something for each Iterable inside the iterable. This would only make sense if iterable was an Iterable<? extends Iterable> (i.e. it would iterate over yet other Iterable objects).

But since you didn't specify a type argument for the argument, you only know that it will iterate over some kind of object (i.e. the base type Object is applicable).

You should try this:

for (Object o : iterable) { 
    System.out.println(o);
}

When read out loud it read as "For each Object o in iterable, print o". Replacing Object in that sentence with Iterable should illustrate what the problem was.


Your loop variable is not of type Iterable. It is supposed to have the type of collection elements. Since the parameter of type Iterable has no generic type argument, your items can be iterated as Object instances:

for (Object o : iterable) { 
    System.out.println(o);
}


You are iterating over iterable. So the type of variable 'i' should be object not Iterable. If you want to have specific type there, use Java Generics.


As others have said, Your trying to iterate over iterators, which would make no sense at all. You need to use not Iterable in the for loop but object in your example. But a much better solution is

private static void printIterable(Iterable<String> iterable) {

    // ERROR: "Type mismatch: cannot convert from element type Object to Iterable"
    for (String i : iterable) { 
        System.out.println(i);
    }
}

(Replace string with the object you want)

0

精彩评论

暂无评论...
验证码 换一张
取 消