[英]What's wrong with this print-iterable method?
private static 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
. 您尝试为
iterable
每个Iterable
做一些事情。 This would only make sense if iterable
was an Iterable<? extends Iterable>
仅当
iterable
Iterable<? extends Iterable>
是iterable
的Iterable<? extends Iterable>
Iterable<? extends Iterable>
(ie it would iterate over yet other Iterable
objects). Iterable<? extends Iterable>
(即,它将在其他Iterable
对象上进行迭代)。
But since you didn't specify a type argument for the argument, you only know that it will iterate over some kind of object (ie the base type Object
is applicable). 但是,由于您没有为参数指定类型参数,因此您只知道它将在某种对象上进行迭代(即,基本类型
Object
适用)。
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
". 当大声读出它读作“对于每一个
Object
o
在iterable
,打印o
”。 Replacing Object
in that sentence with Iterable
should illustrate what the problem was. 用
Iterable
替换该句子中的Object
可以说明问题所在。
Your loop variable is not of type Iterable. 您的循环变量的类型不是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:
由于类型为Iterable的参数没有泛型类型参数,因此您的项目可以作为对象实例进行迭代:
for (Object o : iterable) {
System.out.println(o);
}
You are iterating over iterable. 您正在遍历可迭代。 So the type of variable 'i' should be object not Iterable.
因此,变量“ i”的类型应该是不可迭代的对象。 If you want to have specific type there, use Java Generics.
如果要在此处使用特定类型,请使用Java泛型。
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.
您无需在for循环中使用Iterable,而是在示例中使用object。 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) (用所需的对象替换字符串)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.