Chapter 6: "Collection Considerations" Data Structures with Java, Rick Mercer Answers to Self-Check Questions 6-1 which have errors? c and d -c- can not assign a Double to an Intger -d- can not assign an Object to an Intger 6-2 which are valid? a, b, and c -d- error -e- error 6-3 which generate errors? None 6-4 test method for remove @Test public void testRemove() { Bag names = new ArrayBag(); names.add("Sam"); names.add("Chris"); names.add("Devon"); names.add("Sandeep"); assertFalse(names.remove("Not here")); assertTrue(names.remove("Sam")); assertEquals(0, names.occurencesOf("Sam")); // Attempt to remove after remove assertFalse(names.remove("Sam")); assertEquals(0, names.occurencesOf("Sam")); assertEquals(1, names.occurencesOf("Chris")); assertTrue(names.remove("Chris")); assertEquals(0, names.occurencesOf("Chris")); assertEquals(1, names.occurencesOf("Sandeep")); assertTrue(names.remove("Sandeep")); assertEquals(0, names.occurencesOf("SanDeep")); // Only 1 left assertEquals(1, names.occurencesOf("Devon")); assertTrue(names.remove("Devon")); assertEquals(0, names.occurencesOf("Devon")); } 6-5 remove method in the ArrayBag class // Remove element if it is in this bag, otherwise return false. public boolean remove(E element) { for (int i = 0; i < n; i++) { if (element.equals(data[i])) { // Replace with the element at the send data[i] = data[n - 1]; // Reduce the size n--; return true; // Found--end the search } } // Did not find element "equals" anything in this bag. return false; } 6-6 O(n) 6-7 anObject = aString; // __x___ anInteger = aString; // Can't assign String to Integer anObject = anInteger; // __x___ anInteger = anObject; // Can;t assign Obect to Integer 6-8 All compile 6-9 Integer i = 3; // ___x_____ int i2 = new Integer(3); // ___x_____ Integer i3 = 3.5; // Can't assign Double to Integer int i4 = 3 * new Integer(5); // ____x____ Double d2 = 3.0 * new Integer(3) / 4; // ____x____ Double d = 3; // Need 3.0 rather than 3