Write a method called removeInRange that accepts four parameters: an ArrayList o
ID: 3685905 • Letter: W
Question
Write a method called removeInRange that accepts four parameters: an ArrayList of integers, an element value, a starting index, and an ending index. The method's behavior is to remove all occurrences of the given element that appear in the list between the starting index (inclusive) and the ending index (exclusive). Other values and occurrences of the given value that appear outside the given index range are not affected.
For example, for the list [0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 0, 12, 0, 14, 0, 16], a call of removeInRange(list, 0, 5, 13);should produce the list [0, 0, 2, 0, 4, 6, 8, 10, 12, 0, 14, 0, 16]. Notice that the zeros located at indices between 5 inclusive and 13 exclusive in the original list (before any modifications were made) have been removed.
Method problem: For this problem, you are supposed to write a Java method as described. You should notwrite a complete Java class; just write the method(s) described in the problem statement.
Explanation / Answer
Here is the code for you:
public static void removeInRange(ArrayList al, int ele, int start, int end)
{
ArrayList alDup = new ArrayList();
for(int i = 0; i < start; i++)
alDup.add(al.get(i));
for(int i = start; i < end; i++)
if(al.get(i) != ele)
alDup.add(al.get(i));
for(int i = end; i < al.size(); i++)
alDup.add(al.get(i));
System.out.println(alDup);
al = alDup;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.