public class MyArrList {
public int[] elem;
public int usedSize;
public static int capacity = 10;
public MyArrList(){
this.elem = new int[capacity];
}
//判断是否为空
public boolean isEmpty(){
return this.usedSize == 0;
}
//判断是否为满
public boolean isFull(){
return this.usedSize == capacity;
}
//打印顺序表
public void display(){
//1.判断是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
//2.打印顺序表
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
//在pos位置新增元素
public void add(int pos, int data){
//1.判断是否为满
if (isFull()){
//2.扩容
this.elem = Arrays.copyOf(this.elem,2*capacity);
}
//3.判断位置是否合法
if(pos > this.usedSize || pos < 0){
throw new RuntimeException("pos位置不合法");
}
//4.移动元素
for (int i = this.usedSize - 1; i >= pos; i--) {
this.elem[i+1] = this.elem[i];
}
//5.赋值
this.elem[pos] = data;
//6.use++
this.usedSize++;
}
//判断是否包含某个元素
public boolean contains(int toFind){
//1.判断是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
//2.查找元素
for (int i = 0; i < this.usedSize; i++) {
if (this.elem[i] == toFind){
return true;
}
}
return false;
}
//查找某个元素的对应的位置
public int search(int toFind){
//1.判断是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
//2.查找元素
for (int i = 0; i < this.usedSize; i++) {
if (this.elem[i] == toFind){
return i;
}
}
throw new RuntimeException("找不到该元素");
}
//获取pos位置的元素
public int getPos(int pos){
//1.判断是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
//2.判断位置是否合法
if(pos >= this.usedSize || pos < 0){
throw new RuntimeException("pos位置不合法");
}
//3.返回pos位置元素
return this.elem[pos];
}
//获取顺序表的长度
public int size(){
//1.判断是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
//2.返回长度
return this.usedSize;
}
//给pos位置的元素设为value
public void setPos(int pos, int value){
//1.判断是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
//2.判断位置是否合法
if(pos >= this.usedSize || pos < 0){
throw new RuntimeException("pos位置不合法");
}
//3.赋值
this.elem[pos] = value;
}
//删除第一次出现的关键字
public void remove(int toRemove){
//1.判断是否为空
//2.查找该元素
int index = this.search(toRemove);
//3.移动位置
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
//4.use--
this.usedSize--;
}
//清空顺序表
public void clear(){
//1.判断是否为空
if(isEmpty()){
throw new RuntimeException("顺序表为空");
}
//1.置0
for (int i = 0; i < this.usedSize; i++) {
this.elem[i] = 0;
}
//2.use = 0
this.usedSize = 0;
}
}
public static void main(String[] args) {
MyArrList myArrList = new MyArrList();
System.out.println(myArrList.isEmpty());
myArrList.add(0,1);
myArrList.add(1,2);
myArrList.add(2,3);
myArrList.add(3,4);
myArrList.add(4,5);
myArrList.display();
myArrList.getPos(3);
System.out.println(myArrList.isFull());
myArrList.contains(2);
myArrList.remove(1);
myArrList.display();
}
输出结果:



