用Java写的一个线性表的简单实现
1、接口设计
2、实现类
个中不足,望大家指出。
1、接口设计
package linearTable;
/**
* 线性表的接口设计
* @author fox
*
*/
public interface LinearList {
public boolean isEmpty();
public int size();
public Object get(int index);
public void set(int index,Object e);
public boolean add(int index, Object o);
public boolean add(Object o);
public Object remove(int index);
public void clear();
}
2、实现类
package linearTable;
/**
* 线性表的实现
* @author fox
*
*/
public class LinearListImple implements LinearList {
private Object[] slist;
private int size;
public LinearListImple() {
this(10);
}
public LinearListImple(int length) {
if(length == 0) {
this.slist = new Object[10];
}
this.slist = new Object[length];
}
public boolean isEmpty() {
if(size == 0) {
return true;
} else {
return false;
}
}
public int size() {
return size;
}
public Object get(int index) {
return (Object)slist[index];
}
public void set(int index, Object o) {
checkIndex(index);
slist[index] = o;
}
public boolean add(int index, Object o) {
checkIndex(index);
if(size == slist.length) {
Object[] temp = slist;
this.slist = new Object[temp.length * 2];
for(int j = 0; j < temp.length; j++) {
this.slist[j] = temp[j];
}
}
for(int i = size - 1; i >= index; i--) {
slist[i+1] = slist[i];
}
slist[index] = o;
size++;
return true;
}
public boolean add(Object o) {
return add(size,o);
}
public Object remove(int index) {
checkIndex(index);
Object temp = (Object)slist[index];
for(int i = index; i <= size - 2; i++) {
slist[i] = slist[i+1];
}
slist[size - 1] = null;
size--;
return temp;
}
public void clear() {
if(size != 0) {
for(int i = 0; i < size; i++) {
slist[i] = null;
}
size = 0;
}
}
private void checkIndex(int index) {
if(index > size || index < 0) {
throw new IndexOutOfBoundsException("下标超出当前线性表长度!"+size);
}
}
}
个中不足,望大家指出。