一,前言
hello大家好呀,今天浅略讲讲java的顺序表,其实顺序表大概一个月前就学了,但是由于前段时间期末一直没写博客,但是现在想想其实期末我还是有很多空余时间的,但是由于自己的原因耽误了很多时间现在想来挺后悔的,不过没关系,可以补上,顺序表我们在c语言的阶段详细介绍过(详情移步初级数据结构---顺序表的实现-CSDN博客)其实java实现也大差不差,今天打算水一期啦哈哈,但是也确实没有新东西,但是需要注意我们在实现是运用到了异常的抛出机制和接口,这两部分也不难,这边直接上代码啦,谢谢大家。
二,代码实现
List.java(接口)
public interface List {void Add(int num);void Add(int pos,int num);void Show();int Find(int num);void Delete(int num);void Modify(int source,int num);boolean Full();
}
MyList.java
import java.util.Arrays;
public class MyList implements List {int[] array = new int[6];int NumberSize;MyList() {array[0] = 0;array[1] = 1;array[2] = 2;NumberSize = 3;}public boolean Full() {return this.NumberSize == array.length;}private void grow() {array = Arrays.copyOf(this.array, 2 * this.array.length);}@Overridepublic void Add(int num) {if (Full())grow();array[NumberSize] = num;NumberSize++;}private void Judge(int pos) {if (pos < 0 || pos > NumberSize) {throw new RuntimeException("输入的位置有误");}}@Overridepublic void Add(int pos, int num) {if (Full())grow();try {Judge(pos);for (int i = NumberSize; i >= pos; i--) {array[i + 1] = array[i];}array[pos] = num;NumberSize++;} catch (RuntimeException e) {e.printStackTrace();}}@Overridepublic void Show() {for (int i = 0; i < NumberSize; i++){System.out.println(array[i]);}}private void Judge1(int pos) {if (pos < 0 || pos >= NumberSize)throw new RuntimeException("输入位置不合法,数组元素为个数为:+" + NumberSize);}@Overridepublic int Find(int pos) {try {Judge1(pos);} catch (RuntimeException e) {e.printStackTrace();}return array[pos];}public int FindPos(int num){for (int i = 0; i <NumberSize ; i++) {if (array[i]==num){return i;}}return -1;}@Overridepublic void Delete(int num) {int pos=FindPos(num);for (int i = pos; i <NumberSize ; i++) {array[i]=array[i+1];}NumberSize--;}@Overridepublic void Modify(int pos, int num) {array[pos]=num;}
}
Main.java
public class Main {public static void main(String[] args) {MyList myList=new MyList();myList.Add(3);myList.Add(1,4);myList.Delete(4);myList.Modify(3,4);myList.Show();}
}
三,尾声
再次感谢大家阅读,有错误欢迎大家在评论区指出,下期见