Linuxn00b Linuxn00b - 1 month ago 5
Java Question

Removing all occurrences of an element within an array (setting it to null)

I am attempting to set all occurrences of an element to an array if it is found via a linear search. Let's say the array is as follows:

[Steve, Steve, John, Mike, Gary, Bob, Susan, Mike, Sarah]


Let say if I want to set all occurrences of Mike to null. I've tried the following:

for (int i = 0; i < iTMembers.length; i++) {
if (iTMembers[i].equals(memberName)) {
iTMembers[i] = null;
break;
}
}


The problem however is that it only sets one Mike (String Literal Element) to null and the other one is still present. What can I do? Thanks!

Answer
  1. Remove the break; line because it breaks your loop after the first replacement.
  2. Change

    if (iTMembers[i].equals(memberName))
    

    to

    if (memberName.equals(iTMembers[i]))
    

    because if iTMembers[i] is null, you want a false result, not a NullPointerException.

Comments