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. But I got this error: incompatible types: Object cannot be converted to E. However, if I modify the append method:
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. I'm sure the reason is simple, I just haven't figured it out so far.
Thanks,
CodePudding user response:
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);