简体   繁体   中英

How to remove an object from arrayList

I implemented both add() and remove() methods from my ArrayList Class.

    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();
        }    
    }

However, I don't know how to remove the specific index of my ArrayList of 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)

                }**
            }

Is there any suggestion of how should I get to remove the index of an object of the memberList ? Can I modify my remove() method so that I could directly remove the object instead?

One possibility is to overload the existing remove-method with one that takes an Object-parameter. In the method body you have to iterate through the objects of the list and determine the index of the passed object. Then the existing remove-method is called using the previously determined index to remove the corresponding object.

The following implementation removes the first occurrence of the specified object from the list. The removed object is returned. If the list does not contain the object null is returned.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM