简体   繁体   English

如何在Java中调整数组大小?

[英]How can I resize array in java?

As the title, how can I resize array in java, without importing any library, including ArrayList , Arrays.copyOf ...etc. 作为标题,如何在Java中调整数组大小,而无需导入任何库,包括ArrayListArrays.copyOf ... Arrays.copyOf

Also, I have to resize again and again in my program, with the unknown input data.( ie I have a small array, but when the data increasing, how can I resize it? ) 另外,我必须在程序中使用未知的输入数据一次又一次地调整大小。( 即,我有一个很小的数组,但是当数据增加时,如何调整它的大小?

Java does not have a "resize" option for allocated storage. Java没有分配存储的“调整大小”选项。 You must allocate new storage of the required size and copy the data from the old storage to the new. 您必须分配所需大小的新存储,并将数据从旧存储复制到新存储。

You can use System.arraycopy() to copy the data. 您可以使用System.arraycopy()复制数据。 The ArrayList and Vector classes automatically perform these reallocate and copy operations, so if you don't use them, you are reinventing the wheel. ArrayListVector类自动执行这些重新分配和复制操作,因此,如果您不使用它们,则会重新发明轮子。

java.lang.System is, of course, automatically imported into every java program, so, as required, you don't need import java.lang.System; 当然, java.lang.System会自动导入到每个java程序中,因此,根据需要,您无需import java.lang.System; to implement this. 实现这一点。

Unfortunately, you cant resize an array in java . 不幸的是, 您无法在java中调整数组的大小

Some things you could do are: 您可以做的一些事情是:

  1. When new data is taken in, make a new array and copy the old array + the new data. 接收新数据后,创建一个新阵列并复制旧阵列+新数据。

  2. Use an ArrayList which makes the array bigger as you add data to it. 使用ArrayList可以在向数组添加数据时使数组变大。

  3. Use java.util.Arrays.copyOf(...) . 使用java.util.Arrays.copyOf(...) This returns a bigger array with the contents of the previous array. 这将返回一个更大的数组,其中包含先前数组的内容。

a array is by definition fixed in size, I know many modern languages let you assign the length and change the length dynamically 根据定义,数组的大小是固定的,我知道许多现代语言可以让您分配长度并动态更改长度

but I think what you are looking for is a Vector 但我认为您正在寻找的是向量

https://docs.oracle.com/javase/7/docs/api/java/util/Vector.html https://docs.oracle.com/javase/7/docs/api/java/util/Vector.html

it allows O(1) access (like the array) while beeing dynamic in length 它允许O(1)访问(像数组一样),而长度却是动态的

You can not increase the size of an array once it is declared. 数组一旦声明就不能增加大小。 So you have to use Collection framework in java, may be ArrayList or LinkedList. 因此,您必须在Java中使用Collection框架,可能是ArrayList或LinkedList。

That is what is the difference between Array and ArrayList. 那就是Array和ArrayList之间的区别。 In ArrayList you can add element dynamically,no need to increase it's size. 在ArrayList中,您可以动态添加元素,而无需增加其大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM