如何使用Java编写删除方法?

我需要删除值。 *请参阅插入方法-*

 @Override
public void insertFaculty(Faculty e) {


    setFaculty(e);

    list.add(e.getname());
    list.add(e.getfid());
    list.add(Double.toString(e.getsalary()));

    System.out.println("\n\nFaculty inserted sucessfully.");

}

现在,我需要删除从我的插入方法输入的值 *我尝试删除方法,但不起作用(⊙_⊙;)*

@Override
public void removeFaculty(Faculty e) {


      int i;

    for(i = 1;i<list.size();i=i+1)
    {
        System.out.println(list.get(i));
        if(e.fid.equals(list.get(i)))
        {
            System.out.println("Match found .");
            list.remove(i-1);
            list.remove(i);
            list.remove(i+1);
        }
        else
        {
            System.out.println("Not found .");
        }
    }


}

谢谢 。

评论
adicta
adicta

Consider that when you remove i-1, everything shifts along by 1. So, the thing that was previously at i is now at i-1. And if you remove that one, the thing initially at i+1 will then be at i-1.

So, you could remove i-1 3 times:

// Or loop.
list.remove(i-1);
list.remove(i-1);
list.remove(i-1);

或颠倒移除顺序:

list.remove(i+1);
list.remove(i);
list.remove(i-1);

或清除子列表:

list.subList(i-1, i+2).clear();
点赞
评论
客官,不要
客官,不要

您使用的是哪种列表?为什么列表中保存Faculty对象不是一个好主意,而是将它们的值保存为Strings?

仅添加/删除Faculty对象本身会更容易,因为它不那么容易出错并且更容易理解。

点赞
评论