1

For adding element to an array list, the resizing part of the process, why multiplying factor is much faster than just add a constant,the addition would create a very huge amount of memory box in total, hence its slow, but I suppose the multiplication method also creates a huge amount of memory box as well?

https://www.youtube.com/watch?v=pFWS1pGVn9w&list=PL8FaHk7qbOD7M1Zyio0exJXX9zMlG94Gk&index=8

    private void reSizing(int capacity){
        T[] a = (T[]) new Object[capacity];
        System.arraycopy(items,0,a,0,size);
        items = a;
    }


    public void addLast(T x){
        if(size == items.length){
            reSizing(size*2);
        }
        items[size] = x;
        size = size + 1;
    }

the addition version of the code

    private void reSizing(int capacity){
        T[] a = (T[]) new Object[capacity];
        System.arraycopy(items,0,a,0,size);
        items = a;
    }


    public void addLast(T x){
        if(size == items.length){
            reSizing(size + 1);
        }
        items[size] = x;
        size = size + 1;
    }
Tony
  • 39
  • 6
  • 1
    Well if you only add `1`, you will need to resize every single time a new object is added once you hit the limit the first time. – Nexevis Mar 13 '20 at 12:32
  • See https://stackoverflow.com/a/41155632/1602555 – Karol Dowbecki Mar 13 '20 at 12:35
  • Note that increasing by a factor 2 is not always a good thing, some solutions increase by a percentage, or have a maximum increase (because at a certain point, doubling size will increase memory pressure). – Mark Rotteveel Mar 13 '20 at 19:44

0 Answers0