Java массив изменить размер

Resizing Arrays in Java

Arrays are fixed-size data structures and array sizes can not be changed once they have been initialized. However, in cases where array size needs to be changed, we have to follow one of the given approaches in this tutorial.

1. Using java.util.Arrays.copyOf()

The copyOf(originalArray, newLength) method takes an array and the new length of the array. The copyOf() creates a new array of required newLength and copies the originalArray to the new array using the System.arraycopy() function.

If the new array is smaller in size then copyOf() truncates the remaining items; else if the new array is bigger in size then it pads the remaining indices with nulls. The resulting array is of exactly the same type as the original array.

Note that copyOf() method resizes a one-dimensional array only. For resizing multi-dimensional arrays, there is no generic solution and we need to provide our own logic.

String[] originalArray = ; String[] resizedArray = Arrays.copyOf(originalArray, 10); resizedArray[5] = "F"; System.out.println(Arrays.toString(resizedArray)); //[A, B, C, D, E, F, null, null, null, null]

There are few other APIs to resize the array but internally they follow the same approach, so we can skip them.

Читайте также:  Системами программирования являются java

Another approach is to think again about your design. If an ArrayList is a better fit for such a usecase then consider using the List in place of the array.

Lists are already dynamically resizable, allow index-based accesses and provide great performance.

String[] originalArray = ; ArrayList list = new ArrayList<>(Arrays.asList(originalArray)); list.add("F"); System.out.println(list); //[A, B, C, D, E, F]

Resizing arrays in Java is no different than any other programming language. The resizing process allocates a new array with the specified size, copies elements from the old array to the new one, and then replace the old array with the new one.

In Java, we do not perform explicit memory management so the garbage collection takes care of the old array and frees the memory when it fits.

Источник

Изменение размера массива с сохранением текущих элементов в Java

Изменение размера массива с сохранением текущих элементов в Java

  1. Изменить размер массива в Java
  2. Измените размер массива с помощью метода arraycopy() в Java
  3. Изменение размера массива с помощью метода copyOf() в Java
  4. Изменение размера массива с помощью цикла for в Java

В этом руководстве показано, как изменить размер массива, сохранив все его текущие элементы в Java. Мы включили несколько примеров программ, на которые вы можете ссылаться при выполнении программы в этом поле.

Массив определяется как контейнер, используемый для хранения подобных типов элементов в Java. Это контейнер фиксированного размера, что означает, что если массив имеет размер 10, он может хранить только 10 элементов — это одно из ограничений массива.

В этой статье мы научимся изменять размер массива с помощью некоторых встроенных методов, таких как функции arraycopy() и copyOf() , а также некоторых пользовательских кодов.

Изменить размер массива в Java

Самая верхняя альтернатива динамического массива — это класс структуры коллекции ArrayList , который может хранить любое количество элементов и динамически увеличивается. Первое, что мы можем сделать, это создать ArrayList и скопировать в него все элементы массива. Наконец-то у нас появился новый размер массива. См. Пример ниже:

import java.util.ArrayList; import java.util.List; public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[]12,34,21,33,22,55>;  for(int a: arr)   System.out.print(a+" ");  >  ListInteger> list = new ArrayList<>();  for(int a: arr)   list.add(a);  >  System.out.println("\n"+list);  list.add(100);  System.out.println(list);  > > 
12 34 21 33 22 55 [12, 34, 21, 33, 22, 55] [12, 34, 21, 33, 22, 55, 100] 

Измените размер массива с помощью метода arraycopy() в Java

Java предоставляет метод arraycopy() , который принадлежит классу System и может использоваться для создания копии массива. В этом примере мы создаем новый массив большего размера, а затем копируем в него все исходные элементы массива с помощью метода arraycopy() . Следуйте приведенному ниже примеру программы:

public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[]12,34,21,33,22,55>;  for(int a: arr)   System.out.print(a+" ");  >  int arr2[] = new int[10];  System.arraycopy(arr, 0, arr2, 0, arr.length);  System.out.println();  for(int a: arr2)   System.out.print(a+" ");  >  System.out.println();  arr2[6] = 100;  for(int a: arr2)   System.out.print(a+" ");  >  > > 
12 34 21 33 22 55 12 34 21 33 22 55 0 0 0 0 12 34 21 33 22 55 100 0 0 0 

Изменение размера массива с помощью метода copyOf() в Java

Класс Java Arrays предоставляет метод copyOf() , который можно использовать для создания массива нового размера путем копирования всех исходных элементов массива. Этот процесс принимает два аргумента: первый — это исходный массив, а второй — размер нового массива. См. Пример ниже:

import java.util.Arrays; public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[]12,34,21,33,22,55>;  for(int a: arr)   System.out.print(a+" ");  >  int arr2[] = Arrays.copyOf(arr, 10);  System.out.println();  for(int a: arr2)   System.out.print(a+" ");  >  System.out.println();  arr2[6] = 100;  for(int a: arr2)   System.out.print(a+" ");  >  > > 
12 34 21 33 22 55 12 34 21 33 22 55 0 0 0 0 12 34 21 33 22 55 100 0 0 0 

Изменение размера массива с помощью цикла for в Java

Этот метод прост и является более старым подходом, в котором мы используем цикл for и присваиваем исходные элементы массива вновь созданному массиву на каждой итерации. Мы просто создаем новый массив большего размера и копируем в него все элементы с помощью цикла. См. Пример ниже:

public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[]12,34,21,33,22,55>;  for(int a: arr)   System.out.print(a+" ");  >  int arr2[] = new int[10];  for (int i = 0; i  arr.length; i++)   arr2[i] = arr[i];  >  System.out.println();  for(int a: arr2)   System.out.print(a+" ");  >  > > 
12 34 21 33 22 55 12 34 21 33 22 55 0 0 0 0 

Сопутствующая статья — Java Array

Источник

Java Language Arrays How do you change the size of an array?

The simple answer is that you cannot do this. Once an array has been created, its size cannot be changed. Instead, an array can only be «resized» by creating a new array with the appropriate size and copying the elements from the existing array to the new one.

String[] listOfCities = new String[3]; // array created with size 3. listOfCities[0] = "New York"; listOfCities[1] = "London"; listOfCities[2] = "Berlin"; 

Suppose (for example) that a new element needs to be added to the listOfCities array defined as above. To do this, you will need to:

  1. create a new array with size 4,
  2. copy the existing 3 elements of the old array to the new array at offsets 0, 1 and 2, and
  3. add the new element to the new array at offset 3.

There are various ways to do the above. Prior to Java 6, the most concise way was:

String[] newArray = new String[listOfCities.length + 1]; System.arraycopy(listOfCities, 0, newArray, 0, listOfCities.length); newArray[listOfCities.length] = "Sydney"; 

From Java 6 onwards, the Arrays.copyOf and Arrays.copyOfRange methods can do this more simply:

String[] newArray = Arrays.copyOf(listOfCities, listOfCities.length + 1); newArray[listOfCities.length] = "Sydney"; 

For other ways to copy an array, refer to the following example. Bear in mind that you need an array copy with a different length to the original when resizing.

A better alternatives to array resizing

There two major drawbacks with resizing an array as described above:

  • It is inefficient. Making an array bigger (or smaller) involves copying many or all of the existing array elements, and allocating a new array object. The larger the array, the more expensive it gets.
  • You need to be able to update any «live» variables that contain references to the old array.

One alternative is to create the array with a large enough size to start with. This is only viable if you can determine that size accurately before allocating the array. If you cannot do that, then the problem of resizing the array arises again.

The other alternative is to use a data structure class provided by the Java SE class library or a third-party library. For example, the Java SE «collections» framework provides a number of implementations of the List , Set and Map APIs with different runtime properties. The ArrayList class is closest to performance characteristics of a plain array (e.g. O(N) lookup, O(1) get and set, O(N) random insertion and deletion) while providing more efficient resizing without the reference update problem.

(The resize efficiency for ArrayList comes from its strategy of doubling the size of the backing array on each resize. For a typical use-case, this means that you only resize occasionally. When you amortize over the lifetime of the list, the resize cost per insert is O(1) . It may be possible to use the same strategy when resizing a plain array.)

pdf

PDF — Download Java Language for free

Источник

Как увеличить размер массива java

В Java массивы имеют фиксированный размер, поэтому нельзя просто так увеличить размер уже созданного массива. Однако, можно создать новый массив с большим размером и скопировать в него элементы из старого массива.

Например, если у нас есть массив oldArray размера oldSize , и мы хотим увеличить его размер на increaseSize , можно сделать следующее:

// Создаем новый массив с увеличенным размером int[] newArray = new int[oldSize + increaseSize]; // Копируем элементы из старого массива в новый for (int i = 0; i  oldSize; i++)  newArray[i] = oldArray[i]; > // Теперь можно использовать новый массив // . 

Источник

Оцените статью