我编写了此程序,将一个列表复制到另一个列表,但出现错误。而且在编译其他程序时,我也遇到了与此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>)
答案 0 :(得分:4)
使用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);