JDK-4147188 : Collections: ArrayList does not adequately allow for random access
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 1.2.0
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: generic,windows_95
  • CPU: generic,x86
  • Submitted: 1998-06-09
  • Updated: 2021-03-03
  • Resolved: 1998-06-09
Description

Name: rm29839			Date: 06/09/98


The ArrayList class in the new collections
framework is not useful (in the way that the 
Vector class is) for implementing *sparse*,
variable-size arrays.

The documentation says that the 
add(int index, Object element) method throws 
an IndexOutOfBounds exception when 
(index < 0 || index > size()).  This is fine,
except that there is no setSize(int newSize)
method available.  A developer can increase the
capacity of the ArrayList, but he change the 
actual size, as he can with a Vector.

I don't want to use a Map type, because the 
sequence of elements in the list -- and of those
*not* in the list -- is important.  In other 
words, I want to be able to insert elements into
the list in any order and at any indices, then 
index the list at positions 0 through 
(size() - 1) and get a null back where I did 
not insert a value.
(Review ID: 33274)
======================================================================

Comments
WORK AROUND Name: rm29839 Date: 06/09/98 Use the Vector class. ======================================================================
11-06-2004

PUBLIC COMMENTS .
10-06-2004

EVALUATION Both Vector and ArrayList allow for random access. Neither uses a "sparse implementation" internally. (In both cases, in yoiu can access the nth element, internally you have an array with at least n Objects.) The reporter really wants to know how to initialize an ArrayList to contain n null elements. This is straightforward, and the technique works on any List implementation, not just an arrayList: List l = new ArrayList(Collections.nCopies(n, null)); Creates an ArrayList consisting of n nulls. (n is assumed to be an int.) joshua.bloch@Eng 1998-06-09 A sight twist on this technique can be used to append nulls to a preexisting List. Here's how to grow an ArrayList from 10 elements to 26 (as per the reporter's comments): List l = new ArrayList(10); ... l.addAll(Collections.nCopies(16, null); // Appends 16 nulls to the List While slightly less efficient than Vector.setSize, this technique allows you to choose the initial value, and may be applied to any List. joshua.bloch@Eng 1998-06-10
10-06-1998