AList的具体实现 #CS61B-sp18-2.5
实现一个Array based list,其功能包括获取长度size,添加元素至最后addLast,得到元素get和去除最后一个元素。
设计思路及其实现:
我们都知道在获取数据的时候,直接调用缓存里面的数据比动态计算后再获取数据要快,所以在设计获取size这一数据的时候,我们直接在AList中赋予了一个size属性,在创建的对象的时候将其初始化值为0,并在以后每一次添加元素后自增1就行了。
在CS61B中要求,AList需要有一个初始大小100,所以在new对象的时候会自动把它的定为100,但是size是0。在addLast方法中我们发现我们调用了一个名为resize的方法,由于数组类型的大小是固定的,如果想要扩充数组大小那么就要重新定义一个新的大小的数组然后为其重新赋值。为了简便这一操作,我们直接封装了一个resize方法,使得在以后数组中size==item.length的时候可以方便扩容。方法的实现比较简单,主要是设计比较重要。
另外由于AList的好处在于查询的速度比SLList/DLList要快,但插入相对比较慢。为了解决这一问题,我们最先设计出了一个addLast方法,在size==item.length的时候resize一个数组,使得它的容量加一,这种方法是正确的,但是性能相对来说是比较差的。当遇到长度较长(比如10000)的时候,它每次的resize都会消耗大量的时间。所以我们对其进行了改进,使得它每次长度扩充为原先的两倍,这样的性能是相对比较不错的。
1 public void addLast(int x) {
2 if (size == item.length) {
3 resize(size + 1);
4 }
5 item[size] = x;
6 size += 1;
7 }
具体代码实现如下:
1 /** Array based list.
2 * @author century
3 */
4
5 public class AList {
6 private int[] item;
7 private int size;
8 /** Creates an empty list. */
9 public AList() {
10 item = new int[100];
11 size = 0;
12 }
13
14 /** Inserts X into the back of the list. */
15 public void addLast(int x) {
16 if (size == item.length) {
17 resize(size * 2);
18 }
19 item[size] = x;
20 size += 1;
21 }
22
23 /** Returns the item from the back of the list. */
24 public int getLast() {
25 return item[size - 1];
26 }
27
28 /** Gets the ith item in the list (0 is the front). */
29 public int get(int i) {
30 return item[i];
31 }
32
33 /** Returns the number of items in the list. */
34 public int size() {
35 return size;
36 }
37
38 private void resize(int capacity) {
39 int[] temp = new int[capacity];
40 System.arraycopy(item,0,temp,0,size);
41 item = temp;
42 }
43 /** Deletes item from back of the list and
44 * returns deleted item. */
45 public int removeLast() {
46 int temp = item[size-1];
47 size -= 1;
48 return temp;
49 }
50
51 }

浙公网安备 33010602011771号