Most memory efficient way to grow an array in Java?

前端 未结 12 1278
陌清茗
陌清茗 2020-12-13 19:18

I\'m not too concerned about time efficiency (the operation will be rare), but rather about memory efficiency: Can I grow the array without temporarily having all th

12条回答
  •  情书的邮戳
    2020-12-13 20:14

    AFAIK the only way of growing or reducing an array is doing a System.arraycopy

       /**
        * Removes the element at the specified position in this list.
        * Shifts any subsequent elements to the left (subtracts one from their
        * indices).
        *
        * @param index the index of the element to removed.
        * @return the element that was removed from the list.
        * @throws    IndexOutOfBoundsException if index out of range (index
        *     < 0 || index >= length).
        */
        public static  T[] removeArrayIndex(T[] src, int index) {
            Object[] tmp = src.clone();
    
            int size = tmp.length;
            if ((index < 0) && (index >= size)) {
                throw new ArrayIndexOutOfBoundsException(index);
            }
    
            int numMoved = size - index - 1;
            if (numMoved > 0) {
                System.arraycopy(tmp, index + 1, tmp, index, numMoved);
            }
            tmp[--size] = null; // Let gc do its work
    
            return (T[]) Arrays.copyOf(tmp, size - 1);
        }
    
       /**
        * Inserts the element at the specified position in this list.
        * Shifts any subsequent elements to the rigth (adds one to their indices).
        *
        * @param index the index of the element to inserted.
        * @return the element that is inserted in the list.
        * @throws    IndexOutOfBoundsException if index out of range (index
        *     < 0 || index >= length).
        */
        public static  T[] insertArrayIndex(T[] src, Object newData, int index) {
            Object[] tmp = null;
            if (src == null) {
                tmp = new Object[index+1];
            } else {
                tmp = new Object[src.length+1];
    
                int size = tmp.length;
                if ((index < 0) && (index >= size)) {
                    throw new ArrayIndexOutOfBoundsException(index);
                }
    
                System.arraycopy(src, 0, tmp, 0, index);
                System.arraycopy(src, index, tmp, index+1, src.length-index);
            }
    
            tmp[index] = newData;
    
            return (T[]) Arrays.copyOf(tmp, tmp.length);
        }    
    

提交回复
热议问题