SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:3 | ISBN:9780136091813 | Edition: 2

Question

Write a method called removeInRange that accepts four parameters: a LinkedList, 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 indexes between 5 inclusive and 13 exclusive in the original list (before any modifications were made) have been removed.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class RemoveInRange {

   
	public static List<Integer> removeInRange(List<Integer> list, int value, int begin, int end) {

		int index = begin;
       
        // create new list to store our new elements
		List<Integer> inRange = new ArrayList<Integer>();

        // print the elements from zero to beginning element
		for (int i = 0; i < begin; i++) {
			inRange.add(list.get(i));
		}

        // this while loop runs elements only from begin index to end and compare the
        // each element with value passed in the method parameter
		while (index >= begin && index < end) {
			if (list.get(index) != value) {
				inRange.add(list.get(index));
			}

			index++;
		}

		for (int j = index; j < list.size(); j++) {
			inRange.add(list.get(j));
		}

		return inRange;
	}

	public static void printList(List<Integer> list) {
		System.out.println(Arrays.toString(list.toArray()));
	}

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		Collections.addAll(list, 0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 0, 12, 0, 14, 0, 16);
		printList(removeInRange(list, 0, 5, 13));

	}

}
Output:

[0, 0, 2, 0, 4, 6, 8, 10, 12, 0, 14, 0, 16]

 

0 0

Discussions

Post the discussion to improve the above solution.