数据结构-Java实现线性表
实现线性表有两种方式。第一种是使用数组存储线性表的元素。数组是动态创建的。超过数组的容量时,创建一个新的更大的数组,并且将当前数组中的元素复制到新建的数组中。另一种方法是用链表结构实现。链表由节点组成,每个结点都是动态生成的,用来存储一个元素。所有的结点连接成一个线性表。
本文讲述使用变长数组实现线性表
实现代码
package com.billJiang.array;
import java.util.Arrays;
import java.util.Collection;
/**
* Created by billJiang on 2016/11/30.
* 变长数组
*/
public class ArrayList<T> {
private static final int INITIAL_SIZE = 10;
private int size = 0;
private T[] array;
public ArrayList(int initial) {
if (initial <= 0)
initial = INITIAL_SIZE;
array = (T[]) new Object[initial];
}
public void add(T item) {
//数组扩容
if (size == array.length) {
array = Arrays.copyOf(array, size * 2);
}
array[size++] = item;
}
public T get(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("获取的元素超出了数组的界限");
}
return array[index];
}
public T set(int index, T item) {
T oldItem = this.get(index);
array[index] = item;
return oldItem;
}
public int size() {
return this.size;
}
}
测试代码
package com.billJiang.array;
/**
* Created by billJiang on 2016/11/30.
*/
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Integer> arrayList=new ArrayList<Integer>(3);
arrayList.add(new Integer(1));
arrayList.add(new Integer(2));
arrayList.add(new Integer(3));
System.out.println(arrayList.size());
arrayList.add(new Integer(4));
arrayList.set(3,5);
System.out.println(arrayList.size());
}
}