如何在不知道数组大小的情况下初始化数组? [英] How can I initialize an array without knowing its size?

查看:51
本文介绍了如何在不知道数组大小的情况下初始化数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我必须对输入数组应用一个条件,然后根据过滤条件返回另一个数组作为输出,该数组的大小将更小.

现在的问题是我不知道过滤结果的大小,所以我不能用特定的值初始化数组.而且我不希望它是大尺寸的 null 值,因为我使用的是 array.length;稍后的.

一种方法是首先循环原始输入数组并设置一个计数器,然后使用该计数器长度进行另一个循环并初始化并填充此数组[].但是有没有办法在一个循环中完成这项工作?

解决方案

你不能……数组的大小在 Java 中总是固定的.通常,您会在这里使用 List 的实现而不是使用数组 - 通常是 ArrayList,但还有许多其他可用的替代方法.>

当然,您可以从列表中创建一个数组作为最后一步 - 或者只是更改方法的签名以返回一个 List 开始.

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?

解决方案

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.

这篇关于如何在不知道数组大小的情况下初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆