• The ADTs we’ve used in the past were based on Lists. A Set is more limited. There are no repeat items
• Idea: Store a collection of distinct elements
• S = { x1, x2, … xn }. The order of items does not matter. Ex: a Set of primary colors {“red”, “yellow”, “blue”} is the same as {“blue”, “red”, “yellow”}. The strings are not literally equal, but these Sets represent the same collection of items.
• Equality vs semantic equivalence
• Strict equality: Integer val1 = new Integer(2);
• Integer val2 = new Integer(2);
• What does val1 == val2 return? False, because they store different references. Var1 == var2 returns true if and only if var1 and var2 refer to the same object instance.
• Semantic equivalence: Two instances are semantically equivalent if they represent the same value.
• To test semantic equivalence, use .equals() method, which every class has (inherited for the Object class), and override it to act differently than ==.
• var1.equals(var2) returns true when the two instances represent the same value in a sense defined for the class.
• Want: If we added var1 to a set S, then asked if var2 is contained in S, we would expect the result to be “yes.” S does contain an Integer whose value is 2
• All the elements in a Set are semantically different from each other - you cannot have var1 and var2 in the same set, because they both reference 2
• State: a set of elements
• Operations:
• find(y): Is there an element equivalent to y in the set? If so, return the address. (Not the value - the address) Otherwise, return null.
• add(y): if there is some Xi satisfying y.equals(xi), return false. Otherwise, update state to {x1, …., xn, y} and return true.
• remove(y): if there is some xi satisfying y.equals(xi), update state to {x1, x2, … , x(i-1), x(i+1, …. , xn} and return xi. Otherwise, return null
• Implementing it