Rac*_*hel 4 java generics collections
我正在通过泛型教程,并正在通过示例将对象从数组复制到集合。
码
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o); // Compile time error
}
}
Run Code Online (Sandbox Code Playgroud)
我在想我可以将对象作为参数传递给集合,它应该可以正常工作,但是教程说
到现在为止,您已经学会了避免初学者的错误,即尝试使用Collection作为collection参数的类型。
为什么说将Object作为参数类型传递给Collection是不正确的方法? 更新:
static void fromArrayToCollection(Object[] a, Collection<Object> c) {
for (Object o : a) {
c.add(o); // Compile time error
}
}
Run Code Online (Sandbox Code Playgroud)
他们所指的“初学者错误”是指Collection<Object>您要说的是“任何东西的任何集合/集合”。抽象地说,声明该方法是完全合法的,因为Collection<Object>它根本不能满足采用任何方法的设计目标。
我们希望能够做到这一点:
public static void main(String[] args) {
String[] stringArray = {"A", "B", "C"};
List<String> stringList = new ArrayList<String>();
fromArrayToCollection(stringArray, stringList);
Integer[] intArray = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
fromArrayToCollection(intArray, intList);
}
public static <T> void fromArrayToCollection(T[] array, Collection<T> collection) {
for (T item: array) {
collection.add(item);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您成功了,那将是行不通的Collection<Object>。
您不能将参数类型声明为,Collection<Object>并且不能将其用于上述多种类型,因为泛型类型不是协变的。传入List<String>参数类型为的方法是非法 的Collection<Object>。A Collection<String>不是Collection<Object>。
考虑标准示例:
List<Integer> intList = new ArrayList<Integer>();
List<Object> objList = intList; //doom impending!!!
objList.add("NOTANUMBER");
int i = intList.get(0).intValue(); //runtime exception!
Run Code Online (Sandbox Code Playgroud)
这就是为什么将它声明为Collection<Object>并收取任何东西是非法的。
| 归档时间: |
|
| 查看次数: |
1027 次 |
| 最近记录: |