What is a Set?

A set is an abstract data type that can store information. A set has no repeats and does not arrange the values in any specific order. There are two classifications of sets. Frozen(static) sets are sets that cannot change after creation. Specific operations are allowed on these sets but most aren't because you cannot delete or add elements. The opposite of frozen sets are mutable(dynamic) sets. These sets allow modification after creation and are much more commonly used.

Set Operations in Java

In java, set is an interface which contains methods only inherited from collection. Here are some of the methods:

add() - Adds a value to the collection and returns true if successfully added.

clear() - Removes all elements in the collection.

contains() - Returns true if the set contains the specified element.

isEmpty() - Returns true if set contains no elements.

iterator() - Returns an iterator of elements for use later.

remove() - Removes specified element from the set and return true if successfully removed.

size() - Returns the number of elements in the set.

Bulk Operations on Sets in Java

In java there are also bulk operations on sets. Suppose s1 and s2 are sets for the following examples:

s1.containsAll(s2) - Returns true if all elements in s2 occur in s1.

s1.addAll(s2) - Transforms s1 into the union of s1 and s2.

s1.retainAll(s2) - Transforms s1 to the common elements of s1 and s2.

s1.removeAll(s2) - Transforms s1 to the difference between s1 and s2.

Differences Between Set, Collection and List in Java


1 point
If the numbers 1, 2, 3, 4, 5 were added to a set, what would the output of it be if the set was printed out?