0

I am trying to find out whats happening with my code, I kept getting nullexeptionpointer problem. So I decided to reduce my code and find out whats happening. I want to remove a particular element providing the index to be removed, afterwards, moving all element after it to fill up the space left.

After moving all element, I want to set the last element in the array to null, but i get error and wont compile.

public static void main(String[] args) {


    int [] charSort = new int[] {12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11};

    TextIO.putln("ArrayNum = [12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11]\n");

    TextIO.put("Sorted ArrayNum is:  \n");

    //IntSelecttionSort(charSort);

    TextIO.putln(Arrays.toString(charSort));

    TextIO.put("Enter: "); RemoveShift (charSort, TextIO.getInt());
}


public static void RemoveShift (int[] move, int p){

    for(int i = 0; i<move.length; i++){

        TextIO.put(i+", ");
    }
    TextIO.putln();
    for(int i = p; i<move.length-1; i++){

        move[i]=move[i+1];
    }
    move[move.length-1]=null; // null seems not to work here

    TextIO.putln(Arrays.toString(move));
}   

1 Answer 1

5

int is a primitive, and can't be assigned the value null.

If you want to use null here, you can use the wrapper class Integer instead:

public static void RemoveShift (Integer[] move, int p){ 

Because of autoboxing, you can even initialize your array in the same way:

Integer[] charSort = new Integer[] {12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11};

As @JBNizet points out, a nice alternative if you want to modify an array of Integer is to use an ArrayList instead. That can make your life much easier.

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

1 Comment

If a modifiable array of Integer is what the OP wants, then he should use an ArrayList instead of reinventing the wheel. Not a critique of your answer, just worth mentioning, IMO.

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.