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.
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.
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.Set
interface.
On what basis does Java then decide if the element is part of the set?
The Set / Collection "contract" requires that it use equals(Object)
to determine this. For example, the Collection.contains(Object)
method is specified as follows:
"Returns true if this collection contains the specified element [o]. More formally, returns true if and only if this collection contains at least one element
e
such that(o==null ? e==null : o.equals(e))
."
Different set implementations augment or replace this with the Comparable
/ Comparator
APIs or Object.hashCode()
. The details are in the respective implementation class javadocs.
However, there is no guarantee that a custom Set
implementation will obey the contract.
Does it work solely on the add() and remove() methods to decide if the object still exists in the set?
Other Set
methods (such as contains()
) also need to know if an object is a set member ... if that is what you were asking.