学习数据结构,自己实现了一些数组的基本操作,里面可能会有错误,还望指正
对数组的封装操作,类似于线性表中的顺序存储
/**
* @author NeoSong
* @date Oct 8, 2017
* 5:44:10 PM
* program OF information: 1.自定义类MyArray来封装数组类
* 2.定义操作数组类的方法
*/
public class MyArray
{
private T[] arr;//定义数组,默认初始值为null
private int last;//定义数组长度,默认初始化值为0
private int maxsize;//定义数组长度的最大值
//构造方法初始化变量
public MyArray(){
arr=(T[])new Object[50];//定义长度为50
}
//重载构造方法,maxsize为数组容量
public MyArray(int maxsize){
this.maxsize=maxsize;
arr=(T[])new Object[maxsize];
}
//定义以下基本操作用来操作数组
/*
* 判断数组是否为空
*/
public boolean isEmpty(){
return last==0;
}
/*
* 判断数组是否为满
*/
public boolean isFull(){
return last==maxsize;
}
/*
* 求数组长度
*/
public int count(){
return last;
}
/*
* 1.附加操作
*/
public void attend(T ele){
if(isFull()){
throw new RuntimeException("数组已经满了");
}
arr[last++]=ele;//先赋值,后自增
}
/*
* 2.显示数据
*/
public void display(){
System.out.print("[");
// for(long ele : arr)
// System.out.print(ele+" ");
for(int i=0;i
count()){
throw new RuntimeException("location is wrong");
}
if(isEmpty()){
throw new RuntimeException("数组为空");
}
return arr[i-1];
}
/*
* 5.插入操作
*/
public void insert(int i,T ele){
if(i<1||i>count()){
throw new RuntimeException("location is wrong");
}
if(isFull()){
throw new RuntimeException("数组已经满了");
}
for(int j=last;j>=i;j--){
arr[j]=arr[j-1];
}
arr[i-1]=ele;
last++;//插入之后,别忘了last自增
}
/*
* 6.删除操作
*/
public void delete(int i){
if(i<1||i>count()){
throw new RuntimeException("location is wrong");
}
if(isEmpty()){
throw new RuntimeException("数组为空");
}
for(int j=i-1;j