Java Reference
In-Depth Information
Section 15.3:Advanced Features
14.
When this new version of the class fills to its capacity, it resizes. How much does it grow? Why choose this growth
rate, rather than increasing the capacity by a single element or other constant amount?
15.
What is the benefit of adding an iterator to the list class?
16.
What state does the array list iterator store?
17.
How does the array list iterator know if there are more elements left to examine? What does it do if the client tries to
examine a next element but there are none left to examine?
18.
What is a precondition of the iterator's
remove
method? How does the iterator enforce this precondition, and what
does it do if the precondition is violated?
19.
Write methods called
sum
and
average
that return the sum of all values in the list and the average value as a real num-
ber, respectively. For example, if a variable called
list
stores
[11, -7, 3, 42, 0, 14]
, the call of
list.sum()
should return
63
and the call of
list.average()
should return
10.5
. If the list is empty,
sum
should return
0
and
average
should return
0.0
.
Section 15.4:
ArrayList<E
>
20.
What problem do we encounter when we try to construct an array of type
E
? How do we resolve this problem?
21.
What changes need to be made to the
indexOf
method to search for objects of type
E
in the new list class, and why
are these changes necessary?
22.
What is an annotation? How are annotations useful in writing our
ArrayList<E>
class?
23.
Why is it important to set empty elements to
null
when we are clearing or removing from the list of type
E
, when
we didn't need to clear out these elements in the previous
ArrayIntList
?
24.
What is one benefit of making the list iterator into an inner class?
Exercises
Each of the following exercises is a method to be added to the
ArrayIntList
class from this chapter.
1.
Write a method called
indexOfSubList
that accepts another list
L
as a parameter and returns the starting index of
where
L
first appears in this list, or
1 if it is not found. All elements of
L
must appear in sequence and in the same
order. For example, if variables called
list1
and
list2
store
[11, -7, 3, 42, 0, 14]
and
[3, 42, 0]
respectively, the call of
list1.indexOfSubList(list2)
should return
2
.
2.
Write a method called
replaceAll
that accepts two integer values as parameters and replaces all occurrences of the
first value in the list with the second value. For example, if a variable called
list
stores
[11, -7, 3, 42, 3, 0,
14, 3]
, the call of
list.replaceAll(3, 999);
should change the list to store
[11, -7, 999, 42, 999, 0,
14, 999]
.
3.
Write a method called
reverse
that reverses the order of the elements in the array list. For example, if a variable
called
list
stores
[11, -7, 3, 42, 0, 14, 56]
, the call of
list.reverse();
should change the list to
store
[56, 14, 0, 42, 3, -7, 11]
. An empty or one-element list is not changed by a call to this method.
Search WWH ::
Custom Search