2 Replies Latest reply on Jan 6, 2010 9:42 AM by 800322

    Why does RandomAccess qualify only for ArrayList and Vectors ?

      Hi Guys,

      Just curious a bit about the RandomAccess interface.As per the [API's|http://java.sun.com/j2se/1.5.0/docs/api/java/util/RandomAccess.html] :

      Marker interface used by List implementations to indicate that they support fast (generally constant time) random access

      Now,Is accessing a object using get(index) method of ArrayList the same as get(key) method of Hashtable ?

      Does get(key) method of Hashtable qualify as Random Access ?

      Also,why only List implementations qualify this interface.

      Just curious about the above notations , that's it !! :)

        • 1. Re: Why does RandomAccess qualify only for ArrayList and Vectors ?
          It would have been better if this interface had been called RandomAccessList, to more clearly define its scope.

          Lists provide sequential access, as well as access based on an index number (i.e. random access). Some implementations are much more efficient in providing the latter. These implementations are marked with the RandomAccess interface, for reasons explained in the RandomAccess API docs (optimization for sorting algorithms, primarily).

          For maps, random access is pretty much a given, i.e. the entire purpose of a map is to provide key-based access to its values. So it's pointless to specify a RandomAccess interface for maps, as all maps would implement this by definition.
          • 2. Re: Why does RandomAccess qualify only for ArrayList and Vectors ?
            It goes a little further than this. Those two Lists (ArrayList, Vector) are the only List implementations in the Collections that offer constant-time access to any element, which is what this marker requires. A LinkedList must be traversed to find the desired item, so the retrieval time is proportional to the list's size. ArrayList and Vector are array-backed, and arrays allow direct access.