User
User

Reputation: 1726

How can I correct my method so that it removes string from array?

I am trying to create a method that searches through the 'data' array to find the parameter 'elt'. If it exists, the method deletes it. I cannot figure out how to delete the string "elt". Below is what I have so far.

public class Bag<T> implements Iterable<T> {

private final int MAXLEN = 3;
private int size;
private T[] data; // array

public T remove(T elt) {

    for (T word : data) {
        if (word == "elt")
            data = data.remove(word);
        }
    }       
}

The error I get is "Cannot remove(T) on the array type T[].

Can someone tell me how I can properly remove the string "elt" from the array?

Upvotes: 0

Views: 57

Answers (2)

Andy Turner
Andy Turner

Reputation: 140544

You can't "remove" a value from an array: you cannot change the number of elements in the array once it has been created.

You can, however, change the value of an element, e.g. setting it to null. In order to do this, you'd need the index of the element, so you can't use an enhanced for loop.

If you want a variable-size container, use a mutable List, e.g. ArrayList. You could then simply use list.remove("elt"), no explicit loop required.

Aside: use "elt".equals(word) instead of word == "elt".

Upvotes: 2

dave
dave

Reputation: 12015

data is an array so you cannot remove it in the sense you are trying to do.

You have a few options:

  1. Set the element to null
  2. (1) and move the other elements down
  3. Use a Collection (such as ArrayList) - then you can remove as you'd like

Option (3) would be the simplest. If you are required to use an array, (1) would look something like:

for (int i=0; i<data.length; i++) {
    if ("elt".equals(data[i]) {
        data[i] = null;
    }
}

Upvotes: 2

Related Questions