java封装数组类

7 篇文章 1 订阅
4 篇文章 0 订阅
学习数据结构,自己实现了一些数组的基本操作,里面可能会有错误,还望指正
对数组的封装操作,类似于线性表中的顺序存储
/**  
* @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
     
     
    
    
   
   
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值