亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從arrayList中刪除對象

如何從arrayList中刪除對象

開滿天機 2021-10-20 14:47:36
我從我的類中實現了add()和remove()方法ArrayList。    public void add(Object obj) {        if(data.length - currentSize <= 5) {            increaseListSize();        }        data[currentSize++] = obj;    }    public Object remove(int index){        if(index < currentSize){            Object obj = data[index];            data[index] = null;            int tmp = index;            while(tmp < currentSize){                data[tmp] = data[tmp+1];                data[tmp+1] = null;                tmp++;            }            currentSize--;            return obj;        } else {            throw new ArrayIndexOutOfBoundsException();        }        }但是,我不知道如何刪除 my ArrayListof的特定索引members。                if(temp[0].equals("ADD")) {                    memberList.add(member);                    fileOut.writeLine(member.toString());                    fileLog.writeLine("New member " + member.toString() + " was succesfully added");                }                **else if(temp[0].equals("REMOVE")) {               //memberList.remove(index)                }**            }有什么建議我應該如何刪除 的對象的索引memberList?我可以修改我的remove()方法以便我可以直接刪除對象嗎?
查看完整描述

1 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

一種可能性是用一個接受對象參數的方法重載現有的刪除方法。在方法主體中,您必須遍歷列表的對象并確定傳遞對象的索引。然后使用先前確定的索引調用現有的 remove-method 以刪除相應的對象。


以下實現從列表中刪除第一次出現的指定對象。移除的對象被返回。如果列表不包含對象,則返回null。


public Object remove(Object obj){

    int index = -1;

    for (int i = 0; i < data.length; i++) {

        if (data[i] == obj) {

            index = i;

            break;

        }

    }

    if (index != -1) {

        return remove(index);

    }

    return null;

}


查看完整回答
反對 回復 2021-10-20
  • 1 回答
  • 0 關注
  • 422 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號