[英]Why am I getting an incompatible type error when using the List Iterator's next method but not when I use List's get method?
public static void main(String args[])
{
ArrayList<String> names = new ArrayList<String>();
names.add("Brett");
ArrayList<String> names2 = new ArrayList<String>();
names2.add("John");
append(names, names2);
}
public static <E> void append(List<E> list1, List<E> list2)
{
Iterator list2Iterator = list2.listIterator();
while(list2Iterator.hasNext())
{
list1.add(list2Iterator.next());
}
}
I was asked to append the elements of one list to another.我被要求将一个列表的元素附加到另一个列表中。 I used the list2's iterator to retrieve each element, and passed them to list1's add method.我使用 list2 的迭代器来检索每个元素,并将它们传递给 list1 的 add 方法。 But I got this error: incompatible types: Object cannot be converted to E. However, if I modify the append method:但是我收到了这个错误:不兼容的类型:对象无法转换为 E。但是,如果我修改 append 方法:
public static <E> void append(List<E> list1, List<E> list2)
{
for (int i = 0; i < list2.size(); i++)
list1.add(list2.get(i));
}
it works just fine.它工作得很好。 Both the list iterator and the get method return the same type, but only the latter works.列表迭代器和 get 方法都返回相同的类型,但只有后者有效。 I'm sure the reason is simple, I just haven't figured it out so far.我敢肯定原因很简单,只是到目前为止我还没有弄清楚。
Thanks,谢谢,
The problem is that in your code you are loosing the type parameter when you obtain the list iterator.问题是在您的代码中,您在获取列表迭代器时丢失了类型参数。
public static <E> void append(List<E> list1, List<E> list2) {
Iterator<E> list2Iterator = list2.listIterator();
while(list2Iterator.hasNext()) {
list1.add(list2Iterator.next());
}
}
But you should avoid manually adding all elements of a collections 1 by 1 to another collection.但是您应该避免手动将一个集合的所有元素一一添加到另一个集合中。 Here is a better solution:这是一个更好的解决方案:
list1.addAll(list2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.