顺序表
public class SqListClass <E>{
final int initcapacity = 10;
public E[] data;
public int size;
private int capacity;
@SuppressWarnings("unchecked")
public SqListClass() {
data = (E[]) new Object[initcapacity];
capacity = initcapacity;
size = 0;
}
@SuppressWarnings("unchecked")
private void updatacapacity(int newcapacity) {
E[] newdata = (E[]) new Object[newcapacity];
for(int i = 0;i<size;i++)
newdata[i] = data[i];
capacity = newcapacity;
data = newdata;
}
public void CreatList(E[] a) {
size = 0;
for(int i=0;i<a.length;i++) {
if(size==capacity) {
updatacapacity(size*2);
data[size] = a[i];
size++;
}
}
}
public void Add(E e) {
if(size == capacity)
updatacapacity(2*size);
data[size] = e;
size++;
}
public int size() {
return size;
}
public void SetSize(int nlen) {
if(nlen<0 || nlen>size)
throw new IllegalArgumentException("设置长度:n不在有效范围内");
size = nlen;
}
public E GetElem(int i,E e) {
if(i<0 || i>size-1)
throw new IllegalArgumentException("查找:位置i不在有效范围内");
return (E)data[i];
}
public void SetElem(int i,E e) {
if(i<0 || i>size-1)
throw new IllegalArgumentException("设置长度:n不在有效范围内");
data[i] = e;
}
public int GetNo(E e) {
int i = 0;
while(i<size && !data[i].equals(e))
i++;
if(i>=size)
return -1;
else
return i;
}
public void swap(int i,int j) {
E tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
public void Insert(int i,E e) {
if(i<0 || i>size) {
throw new IllegalArgumentException("插入:位置i不在有效范围内");
}
if(size == capacity)
updatacapacity(2*size);
for(int j=size;j>i;j--)
data[j]=data[j-1];
data[i] = e;
size++;
}