2014-01-12 38 views
0

我想知道我的代碼發生了什麼,我不斷收到nullexeptionpointer問題。所以我決定減少我的代碼,並找出發生了什麼。我想刪除提供要刪除的索引的特定元素,之後移動後面的所有元素以填充剩下的空間。如何聲明一個數組元素爲空?

移動所有元素後,我想將數組中的最後一個元素設置爲null,但是我得到錯誤並且不會編譯。

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

回答

5

intprimitive,並且不能被分配值null

如果你想在這裏使用null,你可以使用包裝類Integer代替:

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

因爲autoboxing的,你甚至可以初始化數組以同樣的方式:

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

正如@JBNizet指出的那樣,如果你想修改一個Integer數組,一個很好的選擇是使用ArrayList來代替。這可以讓你的生活更輕鬆。

+1

如果一個可修改的Integer數組是OP所需的,那麼他應該使用ArrayList而不是重新創建輪子。不要批評你的答案,值得一提的是,國際海事組織。 –

+0

+1您的有用鏈接! –