[英]Generic method with type which extends Iterable doesn't work
Assignment: Write a generic static method print()
that prints the elements of any object that implements the Iterable<E>
interface.作业:编写一个通用静态方法
print()
打印任何实现Iterable<E>
接口的对象的元素。
public class ThisUtil
{
public static <T extends Iterable<T>> void print(T[] anArray) {
ArrayList<String> stringList = new ArrayList<>();
for(T element: anArray)
{
stringList.add(element.toString());
}
String result = String.join(",", stringList);
System.out.println(result);
}
public static void main(String[] args) {
Integer[] list = {1, 2, 5, 9, 3, 7};
ThisUtil.print(list);
}
}
I got error:我收到错误:
no instance(s) of type variable(s) T exist so that Integer conforms to Iterable.
不存在类型变量 T 的实例,因此 Integer 符合 Iterable。
Any help is very appreciated.非常感谢任何帮助。 Thank you advance.
谢谢你提前。
Here:这里:
public static <T extends Iterable<T>> void print(T[] anArray)
you say that you will pass array of elements which type extends Iterable
but you simply want to iterate over this array.你说你将传递类型为 extends
Iterable
的元素数组,但你只是想迭代这个数组。 In your case you can change your method signature to:在您的情况下,您可以将方法签名更改为:
public static <T> void print(T[] anArray)
because arrays can be used in for-each
out of the box.因为数组可以开箱即用地用于
for-each
。
EDIT:编辑:
You are probably looking for something like this:您可能正在寻找这样的东西:
public static <E, I extends Iterable<E>> void print(I iterable) {
ArrayList<String> stringList = new ArrayList<>();
for(E element: iterable) {
stringList.add(element.toString());
}
String result = String.join(",", stringList);
System.out.println(result);
}
but then you cannot use it with arrays since arrays are not Iterable but the can be used in for-each
.但是你不能将它与数组一起使用,因为数组不是 Iterable但可以在
for-each
中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.