Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arraylist Remove() does not work

Tags:

java

arraylist

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);
}
like image 907
user3166873 Avatar asked Dec 11 '22 03:12

user3166873


2 Answers

When you remove the ith element, the i+1th element becomes the ith 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.

like image 159
Eran Avatar answered Dec 22 '22 07:12

Eran


When you remove the ith 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.

like image 26
rgettman Avatar answered Dec 22 '22 06:12

rgettman