A
A
Artyom Kovalenko2020-10-19 22:57:11
Java
Artyom Kovalenko, 2020-10-19 22:57:11

Loop to add elements to an array?

how to create a loop that will add elements to an array? And is it possible to create an array without specifying the type of elements that it will contain in the name?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2020-10-20
Hasanly @azerphoenix

1) Since the length of an array is set when it is created, you cannot add an element to or remove an element from the same array. In fact, a new array is created that contains one element more (n + 1) when adding an element or one element less (n-1) when removing an element
2) Accordingly, you must have methods that accept new elements, create a new one an array of length n+1, loop through the old array and assign its old values ​​to the new one. Well, the last passed element in the arguments is also assigned to a new array, and this new array is returned from the method.

And is it possible to create an array without specifying the type of elements that it will contain in the name?

No. When an array is created, its type is specified.
If you need the ability to use generics, then look towards ArrayList, instead of Array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question