How to set the array length according to the filled data? For example, we generate random numbers in the array i from 1 to 100 . create a for loop and which iterates over these numbers in the array i and if there are the same numbers if (x == y) then this data is transferred to the new array K

Problem: The new array K does not know the number of matched numbers in the array i - therefore, you cannot initially specify its size. How to create a function, where at the new found element from the array i new cell was generated in the array K ?

  • Those. if i [x] == i [y] (== i [z], etc., we have a random number, although all the numbers in the array will be equal), then K [x] = i [x]? - Anton Sorokin
  • Yes. But the problem is that the array K [x] = can be up to 10 elements for example. And found random identical numbers 11. - Yuriy Ivanishchev
  • Uuuh I get it. Use ArrayList, it is dynamic. habr.com/post/128269 - Anton Sorokin
  • one
    the principle is simple, initially we create an array of a certain length, for example (25) and add numbers until it is full, if it is full, then we create a new array, with an increase, let's say n * 2, and copy the data there, change the links. The same principle is used by dynamic classes, or dynamic data structures are used (singly-linked lists, doubly-linked lists) ArraList and a number of other classes - Eugene Fedak
  • one
    But instead of *******, just read about the collections (I’ve put the link above) and use them. - Anton Sorokin

1 answer 1

 public static void main(String[] args) { int[] arr = new int[0]; for (int i = 0; i < 10; i++) { arr = extendArray(arr, i); } System.out.println(Arrays.toString(arr)); } public static int[] extendArray(int[] arr, int value) { int[] newArray = new int[arr.length + 1]; System.arraycopy(arr, 0, newArray, 0, arr.length); newArray[newArray.length - 1] = value; return newArray; }