Java Reference
In-Depth Information
L
ISTING
24.2
MyAbstractList.java
1
public abstract class
MyAbstractList<E>
implements
MyList<E> {
2
protected int
size =
0
;
// The size of the list
size
3
4
/** Create a default list */
5
protected
MyAbstractList() {
6 }
7
8
/** Create a list from an array of objects */
9
protected
MyAbstractList(E[] objects) {
10
for
(
int
i =
0
; i < objects.length; i++)
11 add(objects[i]);
12 }
13
14 @Override
/** Add a new element at the end of this list */
15
public void
add(E e) {
16 add(size, e);
17 }
18
19 @Override
/** Return true if this list doesn't contain any elements */
20
no-arg constructor
constructor
implement
add(E e)
public boolean
isEmpty() {
implement
isEmpty()
21
return
size ==
0
;
22 }
23
24 @Override
/** Return the number of elements in this list */
25
public int
size() {
implement
size()
26
return
size;
27 }
28
29 @Override
/** Remove the first occurrence of the element e
30
* from this list. Shift any subsequent elements to the left.
31
* Return true if the element is removed. */
32
public boolean
remove(E e) {
33
if
(indexOf(e) >=
0
) {
34 remove(indexOf(e));
35
implement
remove(E e)
return true
;
36 }
37
else
38
return false
;
39 }
40 }
The following sections give the implementation for
MyArrayList
and
MyLinkedList
,
respectively.
Design Guide
Protected data fields are rarely used. However, making
size
a protected data field in
the
MyAbstractList
class is a good choice. The subclass of
MyAbstractList
can
access
size
, but nonsubclasses of
MyAbstractList
in different packages cannot
access it. As a general rule, you can declare protected data fields in abstract classes.
protected data field
24.1
✓
✓
Suppose
list
is an instance of
MyList
, can you get an iterator for
list
using
list.iterator()
?
Check
Point
24.2
Can you create a list using
new MyAbstractList()
?
24.3
What methods in
MyList
are overridden in
MyAbstractList
?
24.4
What are the benefits of defining both the
MyList
interface and the
MyAbstractList
class?
Search WWH ::
Custom Search