2
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?

Alex
  • 410
  • 5
  • 13
  • 1
    It's dynamic you don't need to reduce the size if the element is removed the size shrinks or it the element is added the size increase – Lokesh Pandey Apr 30 '18 at 06:08
  • 1
    I don't think you understand what I'm asking. My set method was throwing IndexOutOfBounds errors until I "increased" the size by repeatedly adding nulls, and I'm asking if this is an appropiate solution or if there is a cleaner method and more effecient way of doing this. – Alex Apr 30 '18 at 06:10
  • Yes it is a solution, now why do you use a `List` when you need a specific index ? Do you expect to find a lot of `null` ? Do you thought about using a `Map` ? – AxelH Apr 30 '18 at 06:11
  • @Alex can you include your code which throws `IndexOutOfBounds` – Lokesh Pandey Apr 30 '18 at 06:13
  • He already did, @Lokesh. When he `set` a value with `index >= list.size()` – AxelH Apr 30 '18 at 06:14
  • @AxelH Map solution works well, thanks for the suggestion. – Alex Apr 30 '18 at 06:25
  • In a merge sort I suppose you know the size you need from the size of your input? If so an object array, `Object[]` is an option instead of `ArrayList`. It doesn’t quite give you the type safety since a cast to `T` is required when you take out an element from the array, but should work. – Ole V.V. Apr 30 '18 at 06:52

2 Answers2

2

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);
user7294900
  • 47,183
  • 17
  • 74
  • 157
0

In my opinion the best way is first to create an array of generic type, and after that to create the wrapper with ArrayList.

1.You can see how to create array from generic types here

2.You can see how to create ArrayList from an array here

xyz
  • 482
  • 6
  • 15