java创建动态数组_如何用java语言创建不定长动态数组

[Java] 纯文本查看 复制代码public class intArray

{

private int theSize=0; //元素个数。

private int a_int[]={};

//构造函数: 接受一个int型数组。

public intArray(int a[]){

this.a_int=a; //this.a_int接受a的地址。

this.theSize=a.length;//让本对象中的元素个数等于传入的数组元素个数。

}

//无参构造函数:

public intArray(){

this.theSize=0;

}

//获得thesize。

public int getSize(){

return this.theSize;

}

//获得指定下标的元素的值。

public int getAt(int nIndex){

return this.a_int[nIndex];

}

//设置指定下标的元素的值:

public void SetAt(int nIndex , int newElement){

this.a_int[nIndex] =newElement;

}

//传入一个nIndex

public void add(int nIndex){

int old[] = this.a_int; //让old[]指向this.a_int

this.a_int= new int[this.theSize+1]; //重新构建一个数组。 使这个数组的元素个数比原来多1;

//这里应该是吧old中的每个元素都复制给a_int中的对应元素。

for(int i =0;i

{

a_int[i]= old[i];

}

//判断theSize的值是否大于0 如果大于0那么a_int数组中的最后一个元素值为传入的nIndex值。

if(this.theSize>0){

a_int[this.theSize]=nIndex;

}

//如果不大于0 那么 a_int[0]等于传入的nIndex值;

else{

a_int[0]=nIndex;

}

//然后让thesize++ 意思应该是表明数组长度+1;

this.theSize++;

}

public static void main(String args[]){

intArray array = new intArray(); //new了一个intArray的对象

array.add(1); //添加一个值为1 的元素。

array.add(2);

array.add(3);

array.add(4);

array.add(5);[/i][/i][i][i] //遍历输出(数组)元素。

for(int i = 0;i

System.out.println(array.getAt(i));

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值