United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
JDK-4147188 : Collections: ArrayList does not adequately allow for random access

Details
Type:
Enhancement
Submit Date:
1998-06-09
Status:
Closed
Updated Date:
1998-06-09
Project Name:
JDK
Resolved Date:
1998-06-09
Component:
core-libs
OS:
generic,windows_95
Sub-Component:
java.util
CPU:
x86,generic
Priority:
P4
Resolution:
Not an Issue
Affected Versions:
1.2.0
Fixed Versions:

Related Reports

Sub Tasks

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
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
                                     
1998-06-10
PUBLIC COMMENTS

.
                                     
2004-06-10
WORK AROUND



Name: rm29839			Date: 06/09/98


Use the Vector class.
======================================================================
                                     
2004-06-11



Hardware and Software, Engineered to Work Together