public static ArrayList<String> remove(ArrayList<String> list, int a) {
for(int i = 0; i < list.size(); i++){
list.remove(i);
}
return list;
}
Why doesn't this code remove every element in my array? It seems to skip some. When I print the arraylist at the end it should be blank but it prints it with some elements still in there.
Edit (more code):
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter some a list of words:");
String line = scan.nextLine();
String[] words = line.split(" +");
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<words.length; i++){
list.add(words[i]);
}
System.out.println("Remove words less than how many characters?");
int a = scan.nextInt();
remove(list,a);
System.out.println(list);
}
When you remove the i
th element, the i+1
th element becomes the i
th element. And since you increment i
in each iteration, you skip half of the elements in the list.
This loop would remove all the elements :
for(int i = 0; i < list.size();) {
list.remove(i);
}
Javadoc :
public E remove(int index)
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
Now, if you wish to iterate over all the elements of the list while removing just some of them, you can do the following :
for(int i = 0; i < list.size(); i++) {
if (someCondition) {
list.remove(i);
i--;
}
}
This will make sure you don't skip any element.
When you remove the i
th element, all other elements are shifted down. Then you increment i
anyway, which skips the second element that was originally at i == 1
.
You can remove the elements in a backwards order to avoid this. You can also just call clear()
on the ArrayList
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With