所以我必須創建一個名爲mylistofstrings的類,它聽起來像一串字符串。我必須寫的一種方法是保留所有方法,它只保留列表中與作爲參數輸入的字符串相同的字符串。 for循環似乎跳過了它應該刪除的一半內容,爲什麼? size方法只返回列表中有多少元素,並且很容易發佈。爲什麼這不是爲了循環工作?
public boolean retain(String string) {
if (string == null) {
throw new NullPointerException();
}
MyListOfStrings temp= new MyListOfStrings(this);
int t=this.size();
for (int i=0;i<this.size;i++){
if (string.equals(temp.get(i))!=true){
this.remove(i);
}
}
return t<this.size();
這裏的get方法:
public String get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
return strings[index];
}
和remove方法:
public String remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
String temp = strings[index]; // Save to return at end
System.arraycopy(strings, index + 1, strings, index, size - index - 1);
strings[size - 1] = null;
size--;
return temp;
}
可能的重複[使用For循環從ArrayList中刪除數據](http://stackoverflow.com/questions/10738634/delete-data-from-arraylist-with-a-for-loop) – 2014-09-24 14:33:05