Java Reference
In-Depth Information
MyAbstractList<E>
MyArrayList<E>
-data: E[]
+MyArrayList()
+MyArrayList(objects: E[])
+trimToSize(): void
Creates a default array list.
Creates an array list from an array of objects.
Trims the capacity of this array list to the list's
current size.
Doubles the current array size if needed.
Throws an exception if the index is out of
bounds in the list.
-ensureCapacity(): void
-checkIndex(index: int): void
F
IGURE
24.6
MyArrayList
implements a list using an array.
L
ISTING
24.3
MyArrayList.java
1
public class
MyArrayList<E>
extends
MyAbstractList<E> {
2
public static final int
INITIAL_CAPACITY =
16
;
initial capacity
create an array
3
private
E[] data = (E[])
new
Object[INITIAL_CAPACITY];
4
5
/** Create a default list */
6
public
MyArrayList() {
7 }
8
9
/** Create a list from an array of objects */
10
public
MyArrayList(E[] objects) {
11
for
(
int
i =
0
; i < objects.length; i++)
12 add(objects[i]);
// Warning: don't use super(objects)!
13 }
14
15 @Override
/** Add a new element at the specified index */
16
public void
add(
int
index, E e) {
17 ensureCapacity();
18
19
// Move the elements to the right after the specified index
20
for
(
int
i = size -
1
; i >= index; i--)
21 data[i +
1
] = data[i];
22
23
// Insert new element to data[index]
24 data[index] = e;
25
26
// Increase size by 1
27 size++;
28 }
29
30
/** Create a new larger array, double the current size + 1 */
31
private void
ensureCapacity() {
32
if
(size >= data.length) {
33 E[] newData = (E[])(
new
Object[size *
2
+
1
]);
34 System.arraycopy(data,
0
, newData,
0
, size);
35 data = newData;
36 }
37 }
38
no-arg constructor
constructor
add
ensureCapacity
double capacity
+
1
Search WWH ::
Custom Search