简体   繁体   English

坚持不通过硬编码数组大小来创建Java数组

[英]Stuck on creating Java Arrays by not hardcoding the array size

I want to put this which will be in the main method: 我想把它放在main方法中:

int  numberOfElements =   readFile(args[0],capacities);

the variable numberOfElements is 28. 变量numberOfElements是28。

below is just to let you see a preview of readFile looks like. 下面只是为了让您看到readFile的预览图。

private static int readFile (String filename, String[] capacities)

Basically I want to create the string array called capacities using the variable numberOfElements as its array size: 基本上,我想使用变量numberOfElements作为其数组大小来创建名为capacities的字符串数组:

I'm running into problems on how to do that. 我在执行该操作时遇到了问题。

If you already know the size of the array when it is created the the following works fine: 如果在创建数组时已经知道数组的大小,则可以很好地进行以下操作:

String[] capacities = new String[numberOfElements];

But if you think the size may need to change, I urge you to look into ArrayList . 但是,如果您认为大小可能需要更改,我敦促您研究ArrayList It allows you to add a new element at any time and has a decent search. 它允许您随时添加新元素,并且搜索效果不错。

String[] frobs = new String[numberOfElements];

但是为什么不使用集合呢?

It looks like you are trying to create an array to hold all the results of readFile, but you don't know how big it needs to be until after it already needs to be created. 看起来您正在尝试创建一个数组来保存readFile的所有结果,但是直到创建完该数组之后,您才知道它的大小。

What you need to do is either use a List (for example ArrayList ) which doesn't need an require that you know the size when you create it. 您需要做的就是使用List (例如ArrayList ),它不需要在创建时就知道大小。 Instead these data structures grow as elements are added to them. 相反,这些数据结构随着向其添加元素而增长。

Or you need to write some other function which can read the data file without storing it's values anywhere (perhaps called countFile . All this function would do was count the number of entries you would need in the array in order to hold the data when you actually read and store it using readFile . 或者,您需要编写一些其他函数来读取数据文件,而无需将其值存储在任何地方(也许称为countFile 。此函数要做的就是计算在实际中保存数据时需要在数组中输入的条目数使用readFile读取并存储它。

Do I misunderstand your question? 我会误会你的问题吗? It should be simply 应该很简单

String[] temp = new String[numberOfElements];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM