作业:编写一个通用静态方法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);
}
}
我收到错误:
no instance(s) of type variable(s) T exist so that Integer conforms to Iterable.
非常感谢任何帮助。谢谢您提前。
最佳答案
这里:
public static <T extends Iterable<T>> void print(T[] anArray)
您说您将传递类型扩展Iterable
的元素数组,但您只想迭代该数组。根据您的情况,您可以将方法签名更改为:
public static <T> void print(T[] anArray)
因为数组可以直接用于 for-each
中。
编辑:
您可能正在寻找这样的东西:
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);
}
但是你不能将它与数组一起使用,因为 arrays are not Iterable但可以在for-each
中使用。
关于java - 具有扩展 Iterable 类型的通用方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59100533/