Как увеличить размер массива java
В Java массивы имеют фиксированный размер, поэтому нельзя просто так увеличить размер уже созданного массива. Однако, можно создать новый массив с большим размером и скопировать в него элементы из старого массива.
Например, если у нас есть массив oldArray размера oldSize , и мы хотим увеличить его размер на increaseSize , можно сделать следующее:
Как увеличить размер массива в Java?
Я хочу хранить столько элементов, сколько нужно пользователю в массиве. Но как это сделать? Если бы я должен был создать массив, я должен сделать это с фиксированным размером. Каждый раз, когда в массив добавляется новый элемент, и массив заполняется, я хочу обновить его размер на «1». Я устал от разных типов кода. но это не сработало. Было бы очень полезно, если yall мог бы дать мне некоторые решения относительно этого.. в коде, если это возможно. Спасибо.
How to increase an array's length
I have a quick question. I have an integer array in java that needs its length to vary throughout the class. Specifically, I need it to increase by one in certain situations. I tried it like this.
I would increase the integer variable numberOfSBG when I needed to, but I don’t think this works. Is there any other way?
10 Answers 10
If you don’t want or cannot use ArrayList, then there is a utility method:
that will allow you to specify new size, while preserving the elements.
Arrays in Java are of fixed size that is specified when they are declared. To increase the size of the array you have to create a new array with a larger size and copy all of the old values into the new array.
Alternatively you could use a dynamic data structure like a List.
I would suggest you use an ArrayList as you won’t have to worry about the length anymore. Once created, you can’t modify an array size:
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
First things first:
- In Java, once an array is created, it’s length is fixed. Arrays cannot be resized.
- You can copy the elements of an array to a new array with a different size. The easiest way to do this, is to use one of the Arrays.copyOf() methods.
- If you need a collection of variable size, you’re probably better off using an ArrayList instead of an array.
That being said, there might be situations where you have no other choice than to change the size of an array that is created somewhere outside of your code. 1 The only way to do that is to manipulate the generated bytecode of the code that creates the array.
Proof-of-concept
Below is a small proof-of-concept project that uses Java instrumentation to dynamically change the size of an array 2 . The sample project is a maven project with the following structure:
Main.java
This file contains the target class of which we’re going to manipulate the bytecode:
In the main method, we create a String array of size 1. In the fun method, 4 additional values are assigned outside of the array’s bounds. Running this code as-is will obviously result in an error.
Agent.java
This file contains the class that will perform the bytecode manipulation:
On the bytecode level, the creation of the String array in the Main class consists of two commands:
-
, which pushes an int constant with value 1 onto the stack ( 0x04 ). , which pops the value of the stack and creates a reference array 3 of the same size ( 0xbd ). The above code looks for that combination of commands in the Main class, and if found, replaces the const_1 command with a const_5 command ( 0x08 ), effectively changing the dimensions of the array to 5. 4
pom.xml
The maven POM file is used to build the application JAR and configure the main class and the Java agent class. 5
Build and execute
The sample project can be built using the standard mvn clean package command.
Executing without referencing the agent code will yield the expected error:
While executing with the agent code will yield:
This demonstrates that the size of the array was successfully changed using bytecode manipulation.
1 Such situations came up in questions here and here, the latter of which prompted me to write this answer.
2 Technically, the sample project doesn’t resize the array. It just creates it with a different size than the size specified in code. Actually resizing an existing array while maintaining its reference and copying its elements would be a fair bit more complicated.
3 For a primitive array, the corresponding bytecode operation would be newarray ( 0xbc ) instead.
4 As noted, this is just a proof of concept (and a very hacky one at that). Instead of randomly replacing bytes, a more robust implementation could use a bytecode manipulation library like ASM to insert a pop command followed by an sipush command before any newarray or anewarray command. Some more hints towards that solution can be found in the comments to this answer.
5 In a real-world scenario, the agent code would obviously be in a separate project.
Increasing or Extending an Array Length in 3 ways
Learn about the different ways in which a Java array can be extended or Increasing size of array.
1. Overview
In this tutorial, We’ll see how many ways an array can be extended in java.
The actual array values are stored in contiguous memory locations. The answer may not be promptly obvious.
2. Using Arrays.copyOf
First is Arrays.copyOf method. java.util.Arrays.copyOf() method is in java.util.Arrays class . It copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
See the below model example.
Sample code snippet:
This method takes srcArray which is Integer[] array and an int value elementToAdd . This method returns a new array which a new value-added to it.
Internally copies all srcArray elements into a new array using copyOf method with size of srcArray.length+1 . Here, array last index value added with value ‘0’ and replacing with new value elementToAdd.
On this spot now, We should talk about a few cases on the below code.
If the newLength is greater than srcArray length then Arrays.copyOf() method will copy the extra null values into the destination array.
Extra values filling behaviour will be changed based on the srcArray type. If it is Wrapper or custom classes array then null values will be added.
if srcArray is char then null values and if srcArray is a boolean array then false will be added. The Thumb rule is for extra value filling is with srcArray type default value.
In String class, concat() method uses copyof method internally in java api. And also uses System.arraycopy method inside concat method of String.
3. Using ArrayList
Second, we’ll see using ArrayList. Here we do perform 3 steps.
1) covert srcArray to ArrayList
2) Add newElement to the ArrayList
3) Convert back ArrayList to destArray .
Sample code snippet:
The above program is to add newElement to the array by increasing array size.
Invoking addElementUsingArrayList method.
New destArray values will be as below.
We could see now that a new value-added to the array.
4. Using System.arraycopy
Syntax Structure:
Sample code snippet:
An interesting fact is that System.arraycopy method is used internally in Arrays.copyOf method and increasing the size of ArrayList when it reaches a threshold.
Here we can notice that we moved the elements from the srcArray to destArray and then add the new element to the destArray. But, still, the srcArray holds the original values and this is not modified.
5. Performance Aspect
In the above all discussed solutions, we had to create a new array using possible ways. The reason is that the array holds a contiguous block of memory for super-fast lookup, which is why we cannot simply resize it.
This operation impacts performance but ArrayList is well balanced in resizing the Array when it is actually needed. relation of memory is taken care by JVM .
6. Conclusion:
In this tutorial, we have explored the different ways of adding elements to the end of an array. In other words, increasing or extending the size of an Array.