How can I initialize an array without knowing its size? How can I initialize an array without knowing its size? arrays arrays

How can I initialize an array without knowing its size?


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.


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


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); }