Search code examples
javaarraysallocation

Reallocating array size using type of its element


I have a class attribute which is an Anytype built-in array. At some point I need to reallocate it’s memory to double it, but since it is Anytype, I can’t do:

myArray = new Anytype[myArray.length * 2];

Since the array is already defined, I can access to it’s elements class:

myArray[0].getClass();

My question is: Can I use the fact that I know the class of my array to reallocate it? I know I could use Arrays.copyOf from Java utils, but I want to know if it is possible to reallocate knowing the size your object need, kind of a C-way:

myArray = new myArray[0].getAllocationNeeded()[myArray.length * 2];

P.S: I’m not sure if the title is relevant, please indicate me if you have something more clear


Solution

  • Yes, something like this (assume source is not null or empty):

       public <T> T[] resizeArray(T[] source, int multiplier) {
        T[] newArray = (T[]) Array.newInstance(source.getClass().getComponentType(), source.length * multiplier);
        System.arraycopy(source, 0, newArray, 0, source.length);
        return newArray;
    }
    

    Both:

    • source.getClass().getComponentType()
    • myArray[0].getClass()

    Return the element class.