Linuxn00b Linuxn00b - 1 year ago 57
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;

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 Source
  1. Remove the break; line because it breaks your loop after the first replacement.
  2. Change

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


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download