0

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?

Anderson
  • 23
  • 5
  • https://stackoverflow.com/questions/642897/removing-an-element-from-an-array-java – devric Sep 30 '18 at 23:48
  • Possible duplicate of [Removing an element from an Array (Java)](https://stackoverflow.com/questions/642897/removing-an-element-from-an-array-java) – devric Sep 30 '18 at 23:48

1 Answers1

0

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;
}
Topaco
  • 40,594
  • 4
  • 35
  • 62