Java dynamic array sizes?

前端 未结 18 2174
星月不相逢
星月不相逢 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:29

    As others have said, you cannot change the size of an existing Java array.

    ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:

    • You cannot use [ ... ] to index a list. You have to use the get(int) and set(int, E) methods.
    • An ArrayList is created with zero elements. You cannot simple create an ArrayList with 20 elements and then call set(15, foo).
    • You cannot directly change the size of an ArrayList. You do it indirectly using the various add, insert and remove methods.

    If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )

    If you only really need an array that grows as you are initializing it, then the solution is something like this.

    ArrayList tmp = new ArrayList();
    while (...) {
        tmp.add(new T(...));
    }
    // This creates a new array and copies the element of 'tmp' to it.
    T[] array = tmp.toArray(new T[tmp.size()]);
    

提交回复
热议问题