如何在不知道数量的情况下初始化数组? [英] How can I initialize an array without knowing it size?
问题描述
我有一种情况,我必须在输入数组上应用一个条件,并将另一个数组重新作为输出,根据过滤条件,它将具有更小的尺寸。
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.
现在问题是我不知道过滤结果的大小,所以我无法用特定值初始化数组。我不希望它是大尺寸将为null值因为我使用array.length;稍后的。
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?
推荐答案
你不能......数组的大小总是用Java修复。通常不使用数组,而是在这里使用 List< T>
的实现 - 通常 ArrayList< T>
,但有很多其他选择。
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.
当然,您可以从列表中创建一个数组作为最后一步 - 或者只是将方法的签名更改为返回列表< T>
以开始。
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.
这篇关于如何在不知道数量的情况下初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!