E00X
E00X

Reputation: 13

generic list add method

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;
}

Upvotes: 0

Views: 278

Answers (2)

Adir Dayan
Adir Dayan

Reputation: 1617

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 :)

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

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.

Upvotes: 1

Related Questions