从ArrayList Java中删除

0 java arraylist

我试图从数组列表中删除一个项目,方法是从JList中选择它并单击"删除".

我到目前为止的代码,

buttondeleteContact.addActionListener(new ActionListener() {    
  public void actionPerformed(ActionEvent event) {
    if (contactList.getSelectedIndex() != -1) {
      people.removeElementAt(contactList.getSelectedIndex());   
      People.remove(contactList.getSelectedIndex());
      System.out.println(People);
    }
  });
Run Code Online (Sandbox Code Playgroud)

我知道有些东西名字很差,但是人(小写p)是我的DefaultListModel的名字,而People(大写P)是我的ArrayList的名字.基本上,我只想从数组中删除4行的块.那么,数组中的位置,以及之后的3.

Joa*_*uer 9

虽然List并且ArrayList没有直接(和可访问)removeRange()方法,但是通过提供该subList()方法来消除对这种方法的需要.

subList()提供原始列表的一部分视图.需要注意的重要部分是修改返回的List内容也会修改原始内容List.因此,要删除索引index为的元素index+3,您可以这样做:

myList.subList(index, index+4).clear();
Run Code Online (Sandbox Code Playgroud)

请注意,第二个参数subList()是独占的,因此此subList()调用将返回List大小为4的a.