Nav*_*avy 0 java arrays nullpointerexception
我试图找出我的代码发生了什么,我不断得到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));
}
Run Code Online (Sandbox Code Playgroud)
int是原始的,不能赋值null.
如果你想在null这里使用,你可以使用包装类Integer:
public static void RemoveShift (Integer[] move, int p){
Run Code Online (Sandbox Code Playgroud)
由于自动装箱,您甚至可以以相同的方式初始化阵列:
Integer[] charSort = new Integer[] {12, 5, 7, 4 ,26 ,20 ,1, 6 ,3 ,14, 8, 11};
Run Code Online (Sandbox Code Playgroud)
正如@JBNizet所指出的,如果你想修改一个Integer数组,那么一个不错的选择是使用一个ArrayList替代.这可以让你的生活更轻松.