我從我的類中實(shí)現(xiàn)了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) }** }有什么建議我應(yīng)該如何刪除 的對象的索引memberList?我可以修改我的remove()方法以便我可以直接刪除對象嗎?
1 回答

jeck貓
TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
一種可能性是用一個(gè)接受對象參數(shù)的方法重載現(xiàn)有的刪除方法。在方法主體中,您必須遍歷列表的對象并確定傳遞對象的索引。然后使用先前確定的索引調(diào)用現(xiàn)有的 remove-method 以刪除相應(yīng)的對象。
以下實(shí)現(xiàn)從列表中刪除第一次出現(xiàn)的指定對象。移除的對象被返回。如果列表不包含對象,則返回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;
}
添加回答
舉報(bào)
0/150
提交
取消