05 Arraylist
05 Arraylist
05 Arraylist
index 0 1 2 3 4 5 6 ... 98 99
value 17 932085 -3 100 3 0 0 ... 0 0
size 5
Solving the fixed size – make a Class
public Class IntArray {
private int[] data;
public IntArray (int initialSize) {
data = new int[initialSize];
}
public int get (int index)
return ((index < data.length) ? data[index] : 0);
}
public void set (int index, int val) {
if (index >= data.length)
growArray(index);
data[index] = val;
}
Solving the fixed size – cont
public Class IntArray {
private int[] data;
…
private void growArray (int index) {
int newSize = ??; // how do we determine this?
int[] newData = new int[newSize];
for (int i = 0; i < data.length; i++)
newData[i] = data[i];
data = newData;
}
Using our new class
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 7 5 12 42 0 0 0
size 7
Implementing add (2)
Adding to the middle or front is harder
must shift nearby elements to make room for the new value
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 7 5 12 0 0 0 0
size 6
list.add(3, 42);
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 42 7 5 12 0 0 0
size 7
Note: The order in which you traverse the array matters!
Implementing add (2)
public void add(int index, int value) {
for (int i = size; i > index; i--) {
list[i] = list[i - 1];
}
list[index] = value;
size++;
}
list.add(3, 42);
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 42 7 5 12 0 0 0
size 7
Implementing remove
public void remove(int index) {
for (int i = index; i < size; i++) {
list[i] = list[i + 1];
}
size--;
list[size] = 0; // optional (why?)
}
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 7 5 12 0 0 0 0
size 6
list.remove(2);
index 0 1 2 3 4 5 6 7 8 9
value 3 8 7 5 12 0 0 0 0 0
size 5
Preconditions
What happens if the client tries to access an element
that is past the size but within the bounds of the array?
Example: list.get(11); on a list of 5 elements, capacity 100
We have not addressed this case yet, one approach is to
ask/assume that the user will not do such a thing.
Autoboxing:
ArrayList<Double> grades = new ArrayList<Double>();
// Autoboxing: create Double from double 3.2
grades.add(3.2);
grades.add(2.7);
double sum = 0.0;
for (int i = 0; i < grades.size(); i++) {
//AutoUNboxing from Double to double
sum += grades.get(i);
}
...
Looking ahead: Interfaces
An Java interface specifies which public
methods are available to a user
A class implements an interface if it provides
all the methods in the interface
Interfaces allow for a common behavior
amongst classes, eg the Collection
interface is implemented by many classes
(LinkedList, ArrayList...)
ArrayLists implement the Java Collection
Interface. Let's go look on line...