我写了这个程序将一个列表复制到另一个列表,但是我收到了一个错误。在编译其他程序的同时,我得到了这个Collections.sort()
和Collections.copy()
的错误。任何人都可以帮我解决这个问题吗?
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
class CopyList {
public static void main(String[] args) {
Collection<String> srcstr = new ArrayList<String>();
srcstr.add("New York");
srcstr.add("Atlanta");
srcstr.add("Dallas");
srcstr.add("Madison");
System.out.println("Number of elements: " + srcstr.size());
srcstr.forEach(s->System.out.println(s));
Collection<String> deststr = new ArrayList<String>();
deststr.add("Delhi");
deststr.add("Mumbai");
Collections.copy(srcstr,deststr);
deststr.forEach(s->System.out.println(s));
}
}
我得到的错误:
CopyList.java:17: error: method copy in class Collections cannot be applied to given types;
Collections.copy(srcstr,deststr);
^
required: List<? super T>,List<? extends T>
found: Collection<String>,Collection<String>
reason: cannot infer type-variable(s) T
(argument mismatch; Collection<String> cannot be converted to List<? super T>)
where T is a type-variable:
T extends Object declared in method <T>copy(List<? super T>,List<? extends T>)
使用arraylist更改您的收藏列表。
List<String> srcstr = new ArrayList<String>();
srcstr.add("New York");
srcstr.add("Atlanta");
srcstr.add("Dallas");
srcstr.add("Madison");
List<String> deststr = new ArrayList<String>();
deststr.add("Delhi");
deststr.add("Mumbai");
Collections.copy(srcstr, deststr);