0

I tried to make method which inserts element at the specified position in this list. Then Shifts the element & subsequent elements currently at that position to the Right by adding one to their indices, i know there is shortcut for this method but I am suppose to do it, here what i tried to do but it's not working.

private T a[]; private int count; private int size = 0; public int size() { return size; } public void add(int index,T t) throws Exception { if (index < 0 || index > = a.length){ throw new IndexOutOfBoundsException(); } Object[] temp = new Object[a.length + 1]; for (int k = 0, j = 0; j < temp.length; ++ k, ++ j){ if ( k == index ) { temp[index] = t; --k; } else { temp[j] = a[index]; // } } a = (T[]) temp; } 
2
  • 2
    The trick to shifting is to start from the right, like for (int i = last; i >= first; i--){ temp[i+1]=temp[i];} Commented Sep 15, 2020 at 6:32
  • The result of calling add() is usually that the list ends up larger, so the fact that size remains unchanged is a huge warning sign!! --- Related to that, should the check be index > size instead of index >= a.length? Commented Sep 15, 2020 at 6:36

2 Answers 2

1

The trick to shifting is to start from the right, so:

for (int i = size; i > index; i--) { a[i] = a[i - 1]; } 

btw, when increasing size, normallyyou would double its size,rather than just growing by 1.

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

Comments

0

I corrected your 'for' block, try this:

for (int k = 0, j = 0; j < temp.length; ++k, ++j){ if ( k == index ) { temp[index] = t; --k; index = -1; } else { temp[j] = a[k]; } } 

2 fixes i added:

  • index = -1; - In order to enter the if condition only 1 time, else it will constantly enter the condition
  • temp[j] = a[k]; - replaced to a[k], you was always taking value from a[index] means the same place, this is incorrect.

good luck :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.