javaarrayssizecapacity

Is This The Best Way To "Increase" The Size of An ArrayList?


ArrayList<T> tempArray = new ArrayList<>(size);

I was building a tempArray for my merge sort that will either sort integers or Strings depending on the context. Hence the type T ArrayList.

Then all the sudden I kept running into IndexOutOfBounds errors whenever this was called:

tempArray.set(index, values.get(leftFirst));

After some research I discovered capacity and size don't mean the same thing. So in order to "increase" the size I just added a for loop that runs for size times that adds a null each time:

for (int i = 0; i < size; i++)
    tempArray.add(null);

Is this the best solution?


Solution

  • You are trying to use ArrayList as a map, so just switch to Map and hold your keys as integers:

        Map<Integer, Object> map = new HashMap<>(size);
        map.put(index, values.get(leftFirst));
    

    and then get the index by map.get method:

        map.get(index)
    

    Notice if your index start with a million, you will have ~million null values that won't be used. it seems very unnecessary and wrongly implemented.

    EDIT

    from comments/question, declare your map using T:

    Map<Integer, T> map = new HashMap<>(size);