How can I initialize an array without knowing its size?
Solution 1
You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T>
here - usually ArrayList<T>
, but with plenty of other alternatives available.
You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T>
to start with.
Solution 2
Use LinkedList
instead. Than, you can create an array if necessary.
Solution 3
Just return any kind of list. ArrayList will be fine, its not static.
ArrayList<yourClass> list = new ArrayList<yourClass>();
for (yourClass item : yourArray)
{
list.add(item);
}
Related videos on Youtube
Space Rocker
Updated on July 09, 2022Comments
-
Space Rocker almost 2 years
I have a situation, where I have to apply a criteria on an input array and reuturn another array as output which will have smaller size based upon the filtering criteria.
Now problem is I do not know the size of filtered results, so I can not initialize the array with specific value. And I do not want it to be large size will null values because I am using array.length; later on.
One way is to first loop the original input array and set a counter, and then make another loop with that counter length and initialize and fill this array[]. But is there anyway to do the job in just one loop?
-
Noel M over 13 years
ArrayList
would probably be more appropriate -
Roman over 13 yearswhy would you prefer
ArrayList
toLinkedList
in this situation? -
Roman over 13 years@Noel M: why? I think it wouldn't. We don't know the number of elements. So, with LinkedList every add (i.e. addLast) operation works in O(1) and do really a little job, while
ArrayList
will autoincrease its size several times and these're costly operations. -
Jon Skeet over 13 years@Roman: I just naturally reach for an ArrayList in general. LinkedList would be fine too... it's a more expensive in terms of memory, of course, but it doesn't require copying elements on expansion.
-
Jon Skeet over 13 yearsOn the other hand, with a LinkedList you're creating a Node object for each element. You claim that expansion is a "costly" operation - it's only a matter of creating a new array and copying the existing elements (which can be a fast array copy). I don't think it's simple to say which is uniformly "better" for this situation.
-
Brian over 13 years@Roman: See When to use LinkedList over ArrayList for discussion. That being said, your first inclination should be
ArrayList
.