
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成 数据的增删查改。


public interface IList {
// 新增元素,默认在数组最后新增
void add(int data);
// 在 pos 位置新增元素
void add(int pos, int data) ;
// 判定是否包含某个元素
boolean contains(int toFind);
// 查找某个元素对应的位置
int indexOf(int toFind) ;
// 获取 pos 位置的元素
int get(int pos) ;
//给 pos 位置的元素设为 value
void set(int pos, int value) ;
//删除第一次出现的关键字key
void remove(int toRemove) ;
// 获取顺序表长度
int size() ;
// 清空顺序表
void clear();
// 打印顺序表,注意:该方法并不是顺序表中的方法,为了方便看测试结果给出的
void display() ;
boolean isFull();//判断pos下标是否合法
}import java.util.Arrays;
public class MyArrayList implements IList{
//定义要操作的数组
public int[] elem;
//定义数组存储的数据个数
public int usedSize;
public MyArrayList() {
//初始化数组长度是10
this.elem = new int[10];
}
@Override
//在末尾添加数据
public void add(int data) {
if (isFull()) {
elem = Arrays.copyOf(elem,2*elem.length);
}
this.elem[usedSize] = data;
this.usedSize++;
}
@Override
//在指定位置添加数据
public void add(int pos, int data) {
try {
checkPosOfAdd(pos);
}
catch (PosNotLegalException e) {
e.printStackTrace();
}
if (isFull()) {
elem = Arrays.copyOf(elem,2*elem.length);
}
for (int i = usedSize-1; i >= pos ; i--) {
elem[i+1] = elem[i];
}
elem[pos] = data;
usedSize++;
}
private void checkPosOfAdd(int pos) {
if(pos<0||pos>usedSize){
throw new PosNotLegalException("在pos位置插入元素时Pos位置不合法。。。");//抛出一个异常
}
}
@Override
public boolean contains(int toFind) {
for (int i = 0; i < usedSize; i++) {
if (elem[i] == toFind) {
return true;
}
}
return false;
}
@Override
public int indexOf(int toFind) {
for (int i = 0; i < usedSize; i++) {
if (elem[i] == toFind) {
return i;
}
}
//没有找到
return -1;
}
@Override
public int get(int pos) {
try {
checkPosOfGet(pos);
} catch (PosNotLegalException e) {
e.printStackTrace();
}
return elem[pos];
}
private void checkPosOfGet(int pos) throws PosNotLegalException{
if (pos < 0 || pos >= usedSize) {
throw new PosNotLegalException("get/set获取元素的时候pos位置不合法");
}
}
@Override
public void set(int pos, int value) {
try{
checkPosOfGet(pos);
}catch (PosNotLegalException e){
e.printStackTrace();
}
elem[pos]=value;
}
@Override
public void remove(int toRemove) {
int pos = indexOf(toRemove);
if (pos == -1) {
System.out.println("没有要删除的数字");
}
for (int i = 0; i < usedSize-1; i++) {
elem[i] = elem[i+1];
}
usedSize--;
}
@Override
public int size() {
return usedSize;
}
@Override
public void clear() {
usedSize = 0;
}
@Override
public void display() {
for (int i = 0; i < usedSize; i++) {
System.out.print(elem[i]+" ");
}
System.out.println();
}
@Override
public boolean isFull() {
return false;
}
}//定义一个异常,用于对pos不合法时的报警
public class PosNotLegalException extends RuntimeException{
public PosNotLegalException(){
}
public PosNotLegalException(String msg){
super(msg);
}
}