How can we dynamically allocate and grow an array

前端 未结 8 1820
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 16:01

I am working on a project, but I cannot use any existing java data structures (ie, ArraysList, trees, etc)

I can only use arrays. Therefore, I need to dynamically up

8条回答
  •  生来不讨喜
    2020-12-05 16:41

    you can not increase array size dynamically better you copy into new array. Use System.arrayCopy for that, it better than copying each element into new array. For reference Why is System.arraycopy native in Java?.

    private static Object resizeArray (Object oldArray, int newSize) {
       int oldSize = java.lang.reflect.Array.getLength(oldArray);
       Class elementType = oldArray.getClass().getComponentType();
       Object newArray = java.lang.reflect.Array.newInstance(
             elementType, newSize);
       int preserveLength = Math.min(oldSize, newSize);
       if (preserveLength > 0)
          System.arraycopy(oldArray, 0, newArray, 0, preserveLength);
       return newArray;
    }
    

提交回复
热议问题