Why not remove the element that is less than the variable qVal from ArrayList?

int hVal = (int)aAver; Integer qVal = new Integer(hVal); for(int i =0; i<arrData.size();i++){ if(arrData.get(i)<qVal){ arrData.remove(arrData.get(i)); }; System.out.println("List-> " + arrData.get(i)); } 
  • one
    And you try it like this arrData.remove(i); . - post_zeew
  • it still doesn’t work - Yegor Miaus

1 answer 1

The remove method for an ArrayList looks like this:

 public E remove(int index) 

where index is the index of the item to be deleted.

Accordingly, instead of writing

 arrData.remove(arrData.get(i)); 

need to write delete index

 arrData.remove(i); 

Although once working with Integer , then arrData.remove(arrData.get(i)); it should work, but you need to know and remember: you cannot delete from the collection in the loop; you must go through the collection with an iterator , for example:

 List<String> names = .... Iterator<String> i = names.iterator(); while (i.hasNext()) { String s = i.next(); if (// условие ) { i.remove(); } } 

Well, either run through the collection from the end to the beginning.


As a result, it will be something like this with the iterator:

 Iterator<Integer> i = arrData.iterator(); while (i.hasNext()) { Integer num = i.next(); if(num < qVal){ i.remove(); System.out.println("List-> " + num); } } System.out.println(arrData); 
  • works, but does not remove elements that are less than the qVal variable, but when I change the sign to>, it deletes the elements that are larger - Yegor Myaus
  • @ AlekseyShimansky, Doesn’t it work for the author? Another thing is that it removes only the first entry. - post_zeew
  • @ EgorMäus give an example with the values ​​in your arrData collection and what you type in hVal ... let's see .... in general, you need to use an iterator to delete in a loop - Alexey Shimansky
  • Values ​​in arrData are entered from the keyboard, and hVal is the average of these values. Calculate the arithmetic average of the elements of the array and display all the numbers in the order of their input, which is not less than the arithmetic average. - Yegor Miaus
  • @ YegorMiaus but you have some initial data on which you test ..... but whatever it is ... you need to run around the collection with an iterator, described in the answer about this - Alexey Shimansky