Java dynamic array sizes?

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

    No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:

    int[] oldItems = new int[10];
    for (int i = 0; i < 10; i++) {
        oldItems[i] = i + 10;
    }
    int[] newItems = new int[20];
    System.arraycopy(oldItems, 0, newItems, 0, 10);
    oldItems = newItems;
    

    If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:

    List myclass = new ArrayList();
    myclass.add(new XClass());
    myclass.add(new XClass());
    

    Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:

    class Myclass {
        private int[] items;
    
        public int[] getItems() {
            return items;
        }
    }
    

    you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:

    class Myclass {
        private List items;
    
        public List getItems() {
            return Collections.unmodifiableList(items);
        }
    }
    

提交回复
热议问题