java怎么改变数组的名,如何在Java中扩展数组而不更改其名称

I wonder if it's possible to extend an array in Java but without changing its name, since I have multiple methods linked to this array. I was thinking of creating a new array with the same name but twice as big, and then copy all elements from the first array to the second. Is this possible?

Basically I want to make an array with accounts at a bank, and if the customer creates so many accounds that the array doesn't have enough elements, it should extend itself.

Thank you for any replies!

解决方案

Even if using an ArrayList is probably a good advice in many circumstances, there are perfectly legitimate occasions for using plain old arrays.

In that case, if you need to resize your array, you might want to investigate one of the java.utils.Arrays.copyOf methods. Please note however those won't really resize your array. They will merely create a new array and copy common items.

If the new array has a size greater than the old one, the new items will be initialized to some default value (i.e.: false for boolean[], null for T[] -- see the documentation for details). You have to use those function like that:

myArray = copyOf(myArray, myNewSize);

Remember however that this method will always return a new array. Even if the requested size is the same as the original one. If this in not desirable, you will have to write something like that:

myArray = (myNewSize > myArray.length) ? copyOf(myArray, myNewSize) : myArray;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值