+ 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?
7 Respostas
+ 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/
+ 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.
+ 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
+ 4
@Michael
A linked list, yes. Not a list (the one that arrayList implements).
+ 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);
+ 2
@restoring faith
don't lists work as groups of elements composed by couples of <value, pointer to next node>?
+ 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