Java Reference
In-Depth Information
Self-Test Exercises (continued)
4. Can you use the method set to place an element in an ArrayList at any index
you want?
5. Can you use the two-argument version of the method add to add an element in
an ArrayList at any index you want?
6. Consider the following two method invocations. Are there values of index1 that
are allowed but that are not allowed for index2 ? Are there values of index2 that
are allowed but that are not allowed for index1 ? list is an object of the class
ArrayList<String> .
list.set(index1, "Hello");
list.add(index2, "Hello");
7. If you create an ArrayList with the following statement, can the ArrayList
contain more than 20 elements?
ArrayList<Double> myList = new ArrayList<Double>(20);
Methods in the Class ArrayList
With arrays, the square brackets and the instance variable length are the only tools
automatically provided for you, the programmer. If you want to use arrays for other
things, you must write code to manipulate the arrays. ArrayList s, on the other
hand, come with a selection of powerful methods that can do many of the things for
which you would need to write code in order to do with arrays. For example, the class
ArrayList has a version of the method add that inserts a new element between two
elements in the ArrayList . Most of these methods are described in Display 14.1.
Display 14.1
Some Methods in the Class ArrayList (part 1 of 3)
CONSTRUCTORS
public ArrayList< Base_Type >( int initialCapacity)
Creates an empty ArrayList with the specified Base_Type and initial capacity.
public ArrayList< Base_Type >()
Creates an empty ArrayList with the specified Base_Type and an initial capacity of 10 .
ARRAYLIKE METHODS
public Base_Type set( int index, Base_Type newElement)
Sets the element at the specified index to newElement . Returns the element previously at that
position, but the method is often used as if it were a void method. If you draw an analogy between
the ArrayList and an array a , this statement is analogous to setting a[index] to the value
newElement . The index must be a value greater than or equal to 0 and less than the current size of
the ArrayList . Throws an IndexOutOfBoundsException if the index is not in this range.
(continued)
 
Search WWH ::




Custom Search