Write a method called filterRange that accepts an ArrayList of integers and two
ID: 3825128 • Letter: W
Question
Write a method called filterRange that accepts an ArrayList of integers and two integer values min and max as parameters and removes all elements whose values are in the range min through max (inclusive). For example, if a variable called list stores the values [4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8, 6, 7] the call of filterRange (list, 5, 7); should remove all values between 5 and 7, changing the to store [4, 9, 2, 3, 1, 8]. If no elements in range min-max are found in the list, or if the list is initially empty, the list's contents are unchangedExplanation / Answer
ArrayListValuesTest.java
import java.util.ArrayList;
public class ArrayListValuesTest {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(7);
list.add(9);
list.add(2);
list.add(7);
list.add(7);
list.add(5);
list.add(3);
list.add(5);
list.add(1);
list.add(7);
list.add(8);
list.add(6);
list.add(7);
System.out.println(list);
filterRange(list, 5, 7);
System.out.println(list);
}
public static ArrayList<Integer> filterRange(ArrayList<Integer> list, int min, int max) {
for(int i=0; i<list.size(); i++){
if(list.get(i) >= min && list.get(i) <= max) {
list.remove(i);
i--;
}
}
return list;
}
}
Output:
[4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8, 6, 7]
[4, 9, 2, 3, 1, 8]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.