Java:在集合的遍历中,方法之一为 可以调用Collection接口中的 Object[] toArray()方法 将集合转为数组。这里为什么用 Object[]类型来当返回值,感觉有点怪
巴扎黑2017-04-18 10:51:20
1.Object is the parent class of all objects.
2. When the container class does not know what type will be put in, the implementation design can only use an Object array to store elements.
3. Generics are erased after compilation. In other words, for the JVM, what he sees is Object.
So only Object array can be returned. As for adding generics, the compiler will help you with casts and element detection.
PHPz2017-04-18 10:51:20
Yeah, weird.
So it is recommended to use Collection.toArray(T[] a) to return generics to avoid the problem of forced conversion of Object[].
PHP中文网2017-04-18 10:51:20
Because we don’t know the specific type of elements in the collection. And Object is the parent class of all classes. This is more reasonable.