I’ve been struggling to understand the whole abstract idea behind a custom implementation of a Set interface in Java. In our lectures we’ve implemented functional sets and even flag sets, both of which appear to be inherently recursive lists with functionalities built precisely for a set implementation.
At the end of the day, objects in the set are simply called from the set with a simple for-each loop even though some custom implementations do not remove objects from the list.
For example, in this functional set mentioned, {1,2,3} is represented as Add 3, Add 2, Add 1, Empty while a remove(2) method called directly after would look like Remove 2, Add 3, Add 2, Add 1, Empty. On what basis does Java then decide if the element is part of the set? Does it work solely on the add() and remove() methods to decide if the object still exists in the set?
I hope I’m being coherent enough.
Those implementions are not likely to be particularly instructive for Java Sets. Java sets are mutable … not functional. Anyway, the general specification of the Java Set API is given by the javadoc for the
java.util.Setinterface.The Set / Collection “contract” requires that it use
equals(Object)to determine this. For example, theCollection.contains(Object)method is specified as follows:Different set implementations augment or replace this with the
Comparable/ComparatorAPIs orObject.hashCode(). The details are in the respective implementation class javadocs.However, there is no guarantee that a custom
Setimplementation will obey the contract.Other
Setmethods (such ascontains()) also need to know if an object is a set member … if that is what you were asking.