简体   繁体   中英

Stuck on creating Java Arrays by not hardcoding the array size

I want to put this which will be in the main method:

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

the variable numberOfElements is 28.

below is just to let you see a preview of readFile looks like.

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:

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 . 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.

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. 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 .

Do I misunderstand your question? It should be simply

String[] temp = new String[numberOfElements];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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