Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize an array without knowing its size?

Tags:

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?

like image 717
Space Rocker Avatar asked Dec 26 '10 18:12

Space Rocker


2 Answers

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.

like image 65
Jon Skeet Avatar answered Jan 03 '23 11:01

Jon Skeet


Use LinkedList instead. Than, you can create an array if necessary.

like image 27
Roman Avatar answered Jan 03 '23 09:01

Roman