ArrayLists - Colorado State University

[Pages:26]ArrayLists

Using arrays to store data

Arrays store multiple values of the same type Individual values are referred to by index Convenient to use

a[i] = x; x = a[i];

Limitations of arrays

Fixed in size Don't indicate which values are valid

Using arrays to store data

int[] nums = new int[100]; int size = 0;

We often need to store an unknown number of values.

Arrays can be used for this, but we must count the values. Only the values at indexes [0, size - 1] are relevant. Need to resize the array to store additional values

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

IntArray a = new IntArray(10); int x = a.get(i); // instead of x = a[i]; a.set(i, x); // instead of a[i] = x;

Solving the validity of the entries

Keep track of number of valid entries

Track number of entries in instance variable size Only values at indices 0 ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download