Vector
, ArrayList
, and the whole collections framework was written before generics were a thing in the first place. They didn't really have an alternative at that point, and it had to be left that way for backwards compatibility.
Why using weak typing array for Vector, ArrayList and the whole Java collection framework
-
28-06-2023 - |
Question
I am wondering why didn't the Vector api (as well as others) choose to use strong typing for its underlying array like the code below ? why using week typing Object ? isn't it better with strong typing as the type safety is resolved in compile time ?
public class Vector<E> {
private static final initialCapacity = 2;
protected E[] elementData;
private Vector(Class<E> c) {
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) Array.newInstance(c, initialCapacity);
}
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow