如何在Java中扩展数组而不更改其名称 [英] How to extend an array in Java without changing its name

查看:189
本文介绍了如何在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!

推荐答案

即使使用在这种情况下,如果需要调整数组大小,则可能需要调查

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.

如果新数组的大小大于旧数组的大小,则新项目将被初始化为某个默认值(即:false表示boolean[]null表示T[] -请参阅文档)细节).您必须使用类似的功能:

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); 

但是请记住,此方法将始终返回 new 数组.即使要求的尺寸与原始尺寸相同.如果在 中不希望这样做,则必须编写如下内容:

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;

这篇关于如何在Java中扩展数组而不更改其名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆