Java. (pleace add comments) (i dont need the same soultion like the \"Textbook s
ID: 3825068 • Letter: J
Question
Java. (pleace add comments)
(i dont need the same soultion like the "Textbook solution")
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 list 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 unchanged.
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.ArrayList;
public class FilterRangeTest{
public static void filterRange(ArrayList<Integer> list, int min, int max){
// creating an ArrayList to store all elements that are in range
ArrayList<Integer> range = new ArrayList<>();
for(int i : list){
if(i >= min && i<= max)
range.add(i);
}
// now removing all range elements
list.removeAll(range);
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
// adding all elements in list
int arr[] = {4, 7, 9, 2, 7, 7, 5, 3, 5, 1, 7, 8, 6, 7};
for(int i=0; i<arr.length; i++)
list.add(arr[i]);
System.out.println(list);
filterRange(list, 5, 7);
System.out.println(list);
}
}
/*
Sample run:
[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.