How to define an infinite array? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 2

How to define an infinite array?

Lets say I dont know how many items I gonna hold on an array? How can I do it? Also How to add more item on an array?

30th Aug 2017, 7:57 PM
Abu Musa
Abu Musa - avatar
7 Respuestas
+ 6
@Paul and @Michael are right. If you proceed with Java, you will rarely use these primitive arrays (if ever). The collections are easier to use, especially since Java 8. Some collections are explained in the SoloLearn Java course. And here is another resource to get familiar with them: https://docs.oracle.com/javase/tutorial/collections/
30th Aug 2017, 8:06 PM
Tashi N
Tashi N - avatar
+ 5
There's no such thing as an infinite array, this is a miss-understanding with how lists work. You would need to create a new array of larger size, and copy all elements over from the old array to the new array. (This is what a list does internally anyway). The old array would then be garbage collected. If you have an estimation of how many elements you would use (or a 'maximum' so to speak), it may be better just to declare an array of a very large size and use it as partially filled. Edit: So as @Michael reminded me of, I guess a Linked List is closer to an 'infinite' array, since it's length is truly expandable.
30th Aug 2017, 9:24 PM
Rrestoring faith
Rrestoring faith - avatar
+ 4
use List for that purpose! you can Add and remove items, sort and much more! https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
30th Aug 2017, 7:59 PM
Paul
+ 4
@Michael A linked list, yes. Not a list (the one that arrayList implements).
30th Aug 2017, 11:35 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
you can use a list. I usually use an ArrayList for that purpose. you declare it like List<T> myList = new ArrayList<T> and, whenever you need to add an element to it, you simply go myList.add(muffin);
30th Aug 2017, 8:01 PM
Michael Vigato
Michael Vigato - avatar
+ 2
@restoring faith don't lists work as groups of elements composed by couples of <value, pointer to next node>?
30th Aug 2017, 9:27 PM
Michael Vigato
Michael Vigato - avatar
+ 1
@restoring thank you, I thought that they worked the same way in the memory, but it's actually as you said: when the limit is exceeded, a bigger array is created and the older one is copied into it
31st Aug 2017, 6:13 AM
Michael Vigato
Michael Vigato - avatar