Java Reference
In-Depth Information
Self-Test Exercises
12. (This question refers to the starred section “Generic Methods.” You should skip
this question if you have not yet read that subsection.) Define a generic method
named getMidindex , which is like getMidpoint , but returns the index of the
array midpoint as opposed to the element at the midpoint.
13. (This question refers to the starred section “Inheritance with Generic Classes.”
You should skip this question if you have not yet read that subsection.) Is an
array of type UnorderedPair<String>[] also of type Pair<String>[] ?
Chapter Summary
ArrayList is a parameterized class that is like an array that can grow (and shrink)
while the program is running.
An ArrayList has a number of methods that allow you to use it as a kind of auto-
mated partially filled array.
You can cycle through all the elements in an ArrayList using a for-each loop .
You can define classes with one or more type parameters. Such classes are known as
generic classes .
Answers to Self-Test Exercises
1 . list.add("Hello");
2. instruction.set(5, "Go");
3. instruction.add(5, "Go");
4. No. The index for set must be greater than or equal to 0 and less than the size
of the ArrayList . Thus, you can replace any existing element, but you cannot
place the element at any higher index. This situation is unlike that of an array. If
an array is partially filled to index 10 , you can add an element at index 20 , as long
as the array is that large. With an ArrayList , you cannot add an element beyond
the last-used index.
5. No. The index for add must be greater than or equal to 0 and less than or equal to
the size of the ArrayList . Thus, you can replace any existing element or add an ele-
ment to the end of the list, but you cannot place the element at any higher index. This
situation is unlike that of an array. If an array is partially filled to index 10 , you can
add an element at index 20 , as long as the array is that large. With an ArrayList ,
you cannot add an element beyond one more than the last-used index.
 
Search WWH ::




Custom Search