我想創建一個方法,通過'數據'數組搜索參數'elt'。如果存在,則該方法將其刪除。我無法弄清楚如何刪除字符串「elt」。以下是我到目前爲止。如何糾正我的方法,以便它從數組中刪除字符串?
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);
}
}
}
我得到的錯誤是從陣列ELT‘?
「不能在數組類型T []。誰能告訴我我怎麼能正確地刪除字符串中刪除(T)’
數組的大小是固定的,所以您需要重新創建一個並將內容填充到其中。例如,你可以看看'System.arraycopy'。也不要將String的內容與'=='進行比較,使用'equals'。 –
..或簡單地使用'ArrayList' ... –
這看起來像是一個'ArrayList'的實現。如果你想從一個數組中移除一個元素,你必須將所有具有較高索引的元素移動一個索引。和:比較字符串是通過'someString.equals(otherString)'完成的。 '=='只能用於原始類型 – Paul