Java Reference
In-Depth Information
24.7
Show the length of the array in
MyArrayList
after each of the following statements
is executed.
1 MyArrayList<Double> list = new MyArrayList<>();
2 list.add(
1.5
);
3 list.trimToSize();
4 list.add(
3.4
);
5 list.add(
7.4
);
6 list.add(
17.4
);
24.8
What is wrong if lines 11-12 in Listing 24.3, MyArrayList.java,
for
(
int
i =
0
; i < objects.length; i++)
add(objects[i]);
are replaced by
super
(objects);
or
data = objects;
size = objects.length;
24.9
If you change the code in line 33 in Listing 24.3, MyArrayList.java, from
E[]
new
Data = (E[])(
new
Object[size *
2
+
1
]);
to
E[]
new
Data = (E[])(
new
Object[size *
2
]);
the program is incorrect. Can you ind the reason?
24.10
Will the
MyArrayList
class have memory leak if the following code in line 41 is
deleted?
data = (E[])
new
Object[INITIAL_CAPACITY];
24.11
The
get(index)
method invokes the
checkIndex(index)
method (lines 59-63
in Listing 24.3) to throw an
IndexOutOfBoundsException
if the index is out of
bounds. Suppose the
add(index, e)
is implemented as follows:
public void
add(
int
index, E e) {
checkIndex(index);
// Same as lines 17-27 in Listing 24.3 MyArrayList.java
}
What will happen if you run the following code?
MyArrayList<String> list = new MyArrayList<>();
list.add(
"New York"
);
A linked list is implemented using a linked structure.
Key
Point
Since
MyArrayList
is implemented using an array, the methods
get(int index)
and
set(int index, E e)
for accessing and modifying an element through an index and the
Search WWH ::
Custom Search