简单实现顺序表
package com.mmg.sqltest;
/**
* 手工实现顺序表
* @author MMG
*/
public class MMGList {
//定义变量
private Object[] data;
private int n;
//初始化列表
public MMGList(int length) {
this.data = new Object[length];
this.n = 0;
}
public MMGList(Object[] values) {
this(values.length);
for (int i = 0; i < values.length; i++) {
this.data[i] = values[i];
}
this.n = values.length;
}
//给列表一个初始化的大小
public MMGList() {
this(10);
}
//根据下标获取值
public Object get(int i) {
if (i >= 0 && i < this.n) {
return this.data[i];
} else {
throw new IndexOutOfBoundsException(i + "下标越界");
}
}
//根据下表设置值
public void set(int i, Object obj) {
if (obj == null)
throw new NullPointerException("t==null");
if (i >= 0 && i < this.n) {
this.data[i] = obj;
} else {
throw new IndexOutOfBoundsException(i + "下标越界");
}
}
//插入值
public int insert(Object obj) {
return this.insert(this.n, obj);
}
//根据下表插入值
public int insert(int i, Object obj) {
if (obj == null)
throw new NullPointerException("空指针异常!");
if (i >= 0 && i <= this.n) {
Object src[] = this.data;
if (this.n == data.length) {
this.data = new Object[src.length +1];
for (int j = 0; j < i; j++) {
this.data[j] = src[j];
}
}
for (int j = this.n - 1; j >= i; j--) {
this.data[j + 1] = src[j];
}
this.data[i] = obj;
this.n++;
return i;
} else {
throw new IndexOutOfBoundsException(i + "下标越界");
}
}
//根据下表删除值
public Object remove(int i) {
if (this.n == 0) {
try {
throw new Exception("空表无法删除!");
} catch (Exception e) {
e.printStackTrace();
}
}
if (i >= 0 && i < this.n) {
Object old = this.data[i];
for (int j = i; j < this.n - 1; j++) {
this.data[j] = this.data[j + 1];
}
this.data[this.n - 1] = null;
this.n--;
return old;
} else {
throw new IndexOutOfBoundsException(i + "下标越界");
}
}
//判断是否有对应的值
public boolean contains(Object key) {
for (int i = 0; i < this.n; i++) {
if (key.equals(this.data[i])) {
return true;
}
}
return false;
}
//列表大小
public int size() {
return this.n;
}
//清空列表
public void clear() {
this.n = 0;
}
//判断列表是否为空
public boolean isEmpty() {
return this.n == 0;
}
//打印列表
public void printList() {
for (int i = 0; i < this.n; i++) {
System.out.println(this.data[i]);
}
}
//获取元素在列表中出现的一个的位置
public int indexOf(Object key) {
for (int i = 0; i < this.n; i++) {
if (key.equals(this.data[i])) {
return i;
}
}
return -1;
}
//有序顺序表的合并
public void merge(MMGList listA,MMGList listB,MMGList listC){
int i,j;
i=j=0;//两表均从第一个元素开始依次扫描、比较
while(i<listA.size()&&j<listB.size()){
//将两表中较小的数插入到listC表中
Object o1 = listA.get(i);
Object o2 = listB.get(j);
if(!o1.equals(o2)){
listC.insert(listA.get(i));
i++;
}else{
listC.insert(listB.get(j));
j++;
}
}
//若剩余的是listA表,将表中剩余元素全部插入到listC表中
while(i<listA.size()){
listC.insert(listA.get(i));
i++;
}
//若剩余的是listB表,将表中剩余元素全部插入到listC表中
while(j<listB.size()){
listC.insert(listB.get(j));
j++;
}
}
}
可以自己写个测试类进行测试!