Java dynamic array sizes?

前端 未结 18 2151
星月不相逢
星月不相逢 2020-11-22 04:37

I have a class - xClass, that I want to load into an array of xClass so I the declaration:

xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
my         


        
18条回答
  •  心在旅途
    2020-11-22 05:25

    It is a good practice get the amount you need to store first then initialize the array.

    for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store. if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.

    //Initialize ArrayList and cast string so ArrayList accepts strings (or anything
    ArrayList al = new ArrayList(); 
    //add a certain amount of data
    for(int i=0;i

    doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack

提交回复
热议问题