JDK-8136748 : clone() of legacy collections should have covariant return types
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 8u60
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_8
  • CPU: x86
  • Submitted: 2015-09-15
  • Updated: 2021-03-03
  • Resolved: 2015-09-18
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE REQUEST :
Legacy collections which support clone (Vector/Hashtable/Stack), have specified the return type of clone as Object. This presents problems, because it causes "unchecked" warnings.

For example:

Vector<String> v = ...;
Vector<String> copy = (Vector<String>) v.clone();

results in an "unchecked" warning.


JUSTIFICATION :
The change is minimal. For example, for Vector, it's simply a matter of replacing "Object" with "Vector<E>" in the source code.

There are some workarounds, but none of them are satisfactory:
1) add @SuppressWarnings("unchecked")
=> this needlessly clutters the source code
2) use copy constructors (e.g. "new Vector<String>(v)") instead
=> unlike the clone method, using copy constructors isn't thread-safe
3) replace the usage of legacy collections with modern alternatives
=> again, the problem is that Vector and Hashtable are thread-safe, while typical collections like ArrayList and HashMap aren't. So it's not always easy or even possible to do so


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
The clone() method:
- in Vector must return Vector<E>
- in Hashtable must return HashTable<K, V>
- in Stack must be added & return Stack<E>

ACTUAL -
The clone() methods return Object, which requires casts, which results in compiler warnings.


Comments
But alas, there are some bad source compatibility possibilities in changing the legacy collection classes to have a covariant clone. See the detailed discussion on the core-libs mailing list referenced in JDK-7140820. Closing as a duplicate.
18-09-2015

The clone() method is declared in java.lang.Object and needs to be overridden in subclasses of Object, the signature of the clone thus needs to be one that is applicable for all Objects. Hence, this enhancement doesn't look worthy of spending time. Passing to dev-team for their evaluation.
18-09-2015