// Program to test solutions to problem #6 on the cse143 midterm, summer 2019. // Fill in your solution to retainAll, then compile and run the program. import java.util.*; class ArrayIntList { public void retainAll(Set s) { // fill in your solution here // you can change the name of the parameter } // this is the sample solution public void retainAll2(Set s) { for (int i = 0; i < size; i++) { if (!s.contains(elementData[i])) { for (int j = i; j < size - 1; j++) { elementData[j] = elementData[j + 1]; } size--; i--; } } } private int[] elementData; // list of integers private int size; // current number of elements in the list // post: constructs an empty list of default capacity public ArrayIntList(int capacity) { elementData = new int[capacity]; size = 0; } // post: creates a comma-separated, bracketed version of the list public String toString() { if (size == 0) { return "[]"; } else { String result = "[" + elementData[0]; for (int i = 1; i < size; i++) { result += ", " + elementData[i]; } result += "]"; return result; } } // post: appends the given value to the end of the list public void add(int value) { elementData[size] = value; size++; } } public class Test6 { private static int passCount, failCount; public static void main(String[] args) { int[] data = {23, 34, -6, 98, -12, 7, 44, 23, 67, 23, 12}; Integer[] set = {6, 8, 12, 15, 17, 23, 44}; test(data, set); data = new int[]{}; set = new Integer[]{}; test(data, set); data = new int[]{1, 2, 4, 5, 7, 8}; set = new Integer[]{}; test(data, set); data = new int[]{}; set = new Integer[]{1, 2, 5, 6, 7, 8}; test(data, set); data = new int[]{1, 2, 3, 4, 5}; set = new Integer[]{6, 7, 8, 9, 10}; test(data, set); data = new int[]{1, 2, 3, 4}; set = new Integer[]{1, 2, 3, 4}; test(data, set); data = new int[]{1, 2, 3, 4, 1, 1, 2, 3, 4, 1}; set = new Integer[]{1, 2, 3, 4}; test(data, set); System.out.println("tests passed: " + passCount); System.out.println("tests failed: " + failCount); } public static void test(int[] data, Integer[] set) { ArrayIntList list1 = new ArrayIntList(data.length); ArrayIntList list2 = new ArrayIntList(data.length); Set s = new TreeSet(); s.addAll(Arrays.asList(set)); for (int n : data) { list1.add(n); list2.add(n); } System.out.println("testing..."); System.out.println(" list = " + list1); System.out.println(" set = " + s); try { list1.retainAll(s); list2.retainAll2(s); if (list1.toString().equals(list2.toString())) { passCount++; System.out.println("passed"); } else { failCount++; System.out.println("failed"); } } catch (RuntimeException e) { int line = e.getStackTrace()[2].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); failCount++; System.out.println("failed"); } System.out.println(); } }