我试图找出我的代码发生了什么,我一直遇到 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));
}
最佳答案
int
是 primitive ,并且不能分配值 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 指出的,如果您想修改整数数组,一个不错的选择是使用 ArrayList
反而。这可以让您的生活变得更加轻松。
关于java - 如何声明数组元素为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21077827/