So I have to make a class called mylistofstrings that is exactly what it sounds like, an array of strings. One of the methods I have to write is a retain all method, which retains only the strings in the list that are equal to the string entered as a parameter. The for loop seems to skip half of the things it is supposed to remove, any ideas why? The size method just returns how many elements are in the list and is to simple to post.
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();
Here's the get method:
public String get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
return strings[index];
}
and the remove method:
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;
}