简体   繁体   中英

How to declare an array element null?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM