接着上一节的描述
如何使用代码语言来操作一个顺序表呢?我总结了三个步骤 ----------
步骤一:先将表抽象出来,写一个Java接口,里面包含了对表的一系列基本操作(注意,这里的操作一定是抽象方法,因为我们建立的是一个接口,接口里面只允许存在抽象方法。)
步骤二:写一个Java类来实现刚刚写的Java接口,即是重写接口里面的抽象方法(即你想要对表操作的一个具体逻辑)。
步骤三:写一个测试类,来判断你写的逻辑是否达到要求。
步骤一:创建一个接口IList
public interface IList { public void clear(); public boolean isEmpty(); public int length(); public Object get(int i) throws Exception; public void insert(int i,Object x) throws Exception; public void remove(int i); public int indexOf(Object x); public void display(); }
简单说明一下:1.接口一定是 interface
2.接口里面均为抽象方法。即只有方法名没有方法体。
3.注意观察每一个方法的返回值类型,一定要明白每一个操作的意义。
步骤二:创建一个实体类来实现IList接口
public class SqlList implements IList{ private Object[] listElem;//线性表存储空间,一定是一个数组 private int curLen;//线性表当前的长度,即一共有几个数据 public SqlList(int maxSize) { curLen = 0; listElem = new Object[maxSize]; } @Override public void clear() { curLen = 0; } @Override public boolean isEmpty() { return curLen==0; } @Override public int length() { return curLen; } @Override public Object get(int i) throws Exception{ if(i<0||i>curLen-1) throw new Exception("第"+i+"个元素不存在"); return listElem[i]; } @Override public void insert(int i, Object x)throws Exception { if(curLen==listElem.length) throw new Exception("顺序表已满"); if(i<0||i>curLen) throw new Exception("插入位置不合法"); for(int j = curLen;j>i;j--) listElem[j] = listElem[j-1]; listElem[i] = x; curLen++; } @Override public void remove(int i) { if(i<0||i>curLen-1) throw new Exception("删除位置不合法"); for(int j=1;j<curLen-1;j++) listElem[j] = listElem[j+1]; curLen--; } @Override public int indexOf(Object x) { int j = 0; while(j<curLen && listElem[j].equals(x)) j++; if(j<curLen) return j; else return -1; } @Override public void display() { for(int j=0;j<curLen;j++){ System.out.print(listElem[j]+" "); System.out.println(); } } }
简单说明一下:1、对于顺序表只需要定义两个属性即可,第一个是给予一个存储空间,第二用数据获取当前线性表的长度
2、数据结构对逻辑关系要求十分严格,一定要保证数据之间的关系的逻辑性正确,要确保插入删除的位置合法
3、remove()和indexOf()这两个函数是我手敲的没有在idea里面跑,如果有误可以给我留言,谢谢!
步骤三:建立一个测试类来测试我们的逻辑是否正确
public class test { public static void main(String[] args) throws Exception { SqlList list = new SqlList(10);//首先给表预留一个存储空间 list.insert(0,"JJ's sweet’");//然后一次插入数据 list.insert(1,"林俊杰"); list.insert(2,"杨幂"); list.insert(3,"蔡文静"); list.insert(4,"彭冠英"); list.insert(5,"向日葵"); // list.insert(6,"向日葵"); // list.insert(7,"向日葵"); // list.insert(8,"向日葵"); // list.insert(9,"sss"); list.display();//打印看一下我们的数据是否已经添加成功 boolean empty = list.isEmpty(); System.out.println(empty); list.insert(5,"向日葵"); } }
可以用list去调用我们已经定义的任何方法。
我会将上面的程序打包,有需要的同学私信我【1】即可领取,不用客气。