import java.util.HashSet; import java.util.Set; /** * This utility class contains some methods for (sets of) integers. * * @author Franck van Breugel */ public class Test2F { private Test2F() {} /** * Tests whether the given integer is zero. * * @param number an integer. * @return true if number is zero, false otherwise. */ public static boolean zero(int number) { return number == 0; } /** * Returns the string "empty" if the given set is empty, * and returns the string "nonempty" otherwise. * * @param set a set of integers. * @pre. set != null * @return "empty" if the given set is empty, "nonempty" otherwise. */ public static String empty(Set set) { String result; if (set.isEmpty()) { result = "empty"; } else { result = "nonempty"; } return result; } /** * Tests whether the given set of integers contains an even integer. * For example, for the set { 1, 3, 5, 7 } false is returned and * for the set { 1, 2, 3 } true is returned. * * @param set a set of integers. * @return true if the set contains an even integer, false otherwise. */ public static boolean containsEven(Set set) { boolean containsEven = false; for (Integer element : set) { containsEven = containsEven || element % 2 == 0; } return containsEven; } /** * Returns the sum of the elements of the symmetric difference of the * two given sets. An element belongs to the symmetric difference if * it is contained in one of the two sets, but not in the other. * For example, for the sets
* { 1, 2, 5, 8 } and {1, 3, 8, 9, 10}
* 29 is returned, since 2 + 3 + 5 + 9 + 10 = 29. * * @param first a set of integers. * @pre. first != null * @param second a set of integers. * @pre. second != null * @return the sum of the elements of the symmetric difference of the * two given sets. */ public static int sumOfSymmetricDifference(Set first, Set second) { Set symmetricDifference = new HashSet(); for (Integer element : first) { if (!second.contains(element)) { symmetricDifference.add(element); } } for (Integer element : second) { if (!first.contains(element)) { symmetricDifference.add(element); } } int sum = 0; for (Integer element : symmetricDifference) { sum += element; } return sum; } }