Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8136748

clone() of legacy collections should have covariant return types

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 8u60
    • core-libs

      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.

            darcy Joe Darcy
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: