0

So I want to insert a value in a specific index, that mean I would throw exception if the index I want to insert is not exist or bigger than size, otherwise, I would use this method to ensure the capacity of the array is not null:

private void ensureCapacity(int size_wanted)
{
  int max_capacity = storage.length;
  if (size_wanted > max_capacity) 
  {
    max_capacity = max_capacity * GROW_FACTOR +1; 
    storage = Arrays.copyOf(storage, max_capacity); // increases array size + copy contents
  } 
}

Then at this point, I suppose to extend the array and already made a copy of my original with the increased size already, right?

All I need to do is using a loop and shift everything to the right by one, to leave space for the index I want to insert at, correct?

4
  • Are you trying to build ArrayList? Commented Oct 3, 2012 at 4:26
  • I building a dynamic array that mimic arraylist Commented Oct 3, 2012 at 4:27
  • ArrayList contains dynamic array implementation you are doing is already there. Commented Oct 3, 2012 at 4:28
  • "not exist or bigger than size". You mean >= size actually, remembering that indexes are 0-based. Commented Oct 3, 2012 at 10:26

2 Answers 2

1

You can use System.arrayCopy to move array like that. but why are you rebuilding existing functionality provided by ArrayList

Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to use a loop; you can use the method System.arraycopy to move elements within an array. It correctly handles overlapping ranges:

System.arraycopy(storage, insertPos, storage, insertPos+1, oldSize - insertPos);

2 Comments

But then again I cant put the last 2 argument inside, since I cant change an already prep method.
@RyokoNela - After calling ensureCapacity, call System.arraycopy (using whatever variable names you are using). Then you assign the new value to the slot that was just created: storage[insertPos] = insertValue;.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.