forked from HarryDulaney/intro-to-java-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyAbstractList.java
109 lines (96 loc) · 2.54 KB
/
MyAbstractList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package ch_24.exercise24_01;
import java.util.Iterator;
public abstract class MyAbstractList<E> implements MyList<E> {
protected int size = 0; // The size of the list
/**
* Create a default list
*/
protected MyAbstractList() {
}
/**
* Create a list from an array of objects
*/
protected MyAbstractList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
/**
* Add a new element at the end of this list
*/
@Override
public void add(E e) {
add(size, e);
}
/**
* Return true if this list doesn't contain any elements
*/
@Override
public boolean isEmpty() {
return size == 0;
}
/**
* Return the number of elements in this list
*/
@Override
public int size() {
return size;
}
/**
* Remove the first occurrence of the element e
* from this list. Shift any subsequent elements to the left.
* Return true if the element is removed.
*/
@Override
public boolean remove(E e) {
if (indexOf(e) >= 0) {
remove(indexOf(e));
return true;
} else
return false;
}
/*--------------------------------------------- Exercise24_01 ---------------------------------------------------*/
/**
* Adds the elements in otherList to this list.
* Returns true if this list changed as a result of the call
*/
@Override
public boolean addAll(MyList<E> otherList) {
int startSize = size;
for (E e : otherList) {
if (!contains(e)) {
add(e);
}
}
return size == startSize;
}
/**
* Removes all the elements in otherList from this list
* Returns true if this list changed as a result of the call
*/
@Override
public boolean removeAll(MyList<E> otherList) {
boolean changed = false;
for (E e : otherList) {
boolean removed = remove(e);
if (removed) {
changed = true;
}
}
return changed;
}
/**
* Retains the elements in this list that are also in otherList
* Returns true if this list changed as a result of the call
*/
@Override
public boolean retainAll(MyList<E> otherList) {
boolean changed = false;
for (E e : this) {
if (!otherList.contains(e)) {
remove(indexOf(e));
changed = true;
}
}
return changed;
}
}