English 中文(简体)
在数组 Java 中删除
原标题:Delete in array Java

I have that function where i want the user to pick a number of all schedules to delete one. My logic for delete is to find the i that I want to delete and then swap the last one schedule of my array with the i one, and then the last one to be null.

当我测试我的程序时, 当我想删除我最后一个阵列的时候, 我看到了一切正常, 但是当我试图删除其它东西时, 日蚀中会出现一个错误。

Exception in thread "main" java.lang.NullPointerException I cant figure out what s happening. I have reviewed my code a lot of times.

 public void ScheduleDelete(){
    StandardInputRead readDeleteSchedule = new StandardInputRead();

    int deleteScheduleNum =readDeleteSchedule.readPositiveInt("Enter the schedule number you want to delete: ");
    for(int i=0;i<scheduleSize;i++){
        if(deleteScheduleNum==this.scheduleList[i].getScheduleNum()){
            this.scheduleList[i]= this.scheduleList[this.scheduleSize-1];
            this.scheduleList[i].setScheduleNum(i);
            this.scheduleList[this.scheduleSize-1]= null;
        }
    }
    this.scheduleSize--;
}
最佳回答

当您第二次将元素与最后一个元素互换时,您将以 null 替换该元素(因为您刚刚将数组的最后元素设置为 null 。所以,当您想要使用此元素时,您正在以无效引用操作,因此是例外 。

您需要跟踪您在数组中有多少个 < em > 激活 < / em > 元素, 然后用最后一个 < em > 激活 < / em > 元素交换元素 。

或者,您可以使用动态收藏(例如列表),因为您只存储活动元素,因此不需要对活动元素进行直截了当的跟踪。

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签