This is the lecture note of CS61B - Lecture 7.
We have already seen how we can harness recursive class definition to build an expandable list, ie. the IntList
, the SLList
, and the DLList
.
Now let us stop continuing it and try to use another basic data structure, array, to build list, which is called AList
. You will find these two kinds of lists have differnet pros and cons.
AList: Array-based List
The data structure of DLList
we have talked in the previous lecture is pretty beautiful. And it also has fast operations like addFirst
, addLast
etc. So why should we try to build AList?
Let's see a limitation of DLList.
1. Naive AList
🐹 Retrieval from any postion of an array is very fast.
1 | // We only do back operations in the lecture. Project 1 will give you |
2. removeLast( ) method
The answer is we only need to change size.
1 | /** Deletes item from back of the list and returns deleted item. */ |
3. Resizing Arrays
When the array gets too full, just make a new array!
🦉 Resizing process:
- int[ ] a = new int[newSize]
- System.arraycopy( )
- a[size] = targetNum
- items = a
- size += 1
Let's implement this process.
1 | private void resize(int capacity) { |
Performance Problem 1
The big issue here is that how to set a proper capacity as the parameter of resize method?
Let's do an experiment to test the speed of resizing when using two different strategies.
- one is resize(size + 10)
- another is resize(2 * size)
Performance Problem 2
There is another performance problem. Suppose we have a very rare situation:
- Insert 1,000,000,000 items.
- Then remove 990,000,000 items.
Our data structure will handle this spike of events as well as it could, but afterwards there is a problem - a waste of space!
You will implement this during project 1.
Final Code
Finally, let's make AList generic, and we will get the following code.
1 | public class AList<Item> { |
No Loitering
The last thing we should notice is loitering. Different from int[]
, when using Item[]
we should null out the deleted items manually to save memory usage.