# Sets

In this section, we'll discuss sets. Sets are great for storing data that have no repeats. As you've seen throughout the course so far, many data sturcuters have similar features, but always have a specific distinctino that makes them more appropriate to use depending on the situation.

## Sets

We'll want to use sets when we know that all of our data is unique.

Syntax:

Set<Object> set = new HashSet<Object>();

This is how we declare Sets in Java. We declared a Set with the name set, of type "Object", which, in this case, is a place holder for a data type such as Integer or String (or something of the sort).

There are many useful methods that we can do with Sets in Java. These methods will help us add and remove elements, as well as examine our Set.

Method 1:

s.add()

This method will add whatever element is in the parenthesis into the Set. For example, if we have an integer Set with elements {1,2,3,4,5}, and we write s.add(6), the new value of s is {1,2,3,4,5,6}

Method 2:

s.remove()

This method will remove the whatever element is in the parenthesis from the Set. Take the example where we had

s = {1,2,3,4,5}. Then after we take s.remove(5), we will get s={1,2,3,4}. Remember, Sets are unordered! As a consequence, we must specify exactly what we are removing.

Method 3:

s.contains()

This method will return either true or false, depending on if the Set contains the element in the parenthesis. For example, if we have s = {1,2,3,4,5} and we write s.contains(6), the method will return false.

More Methods:

There are many other more specific methods we can use. For more details, visit the official java library by Oracle!

Iteration: As with any data structure, iteration is always important. How do we iterate through a Set?

Example 1:

{

Set<Integer> s = new HashSet<Integer>();

s.add(1);

s.add(2);

s.add(3);

s.add(4);

for(Integer item: s){

System.out.println(item);

}

}

When we want to iterate over a Set, we can use an enhanced for loop, or "for-each" loop to do so. This will allow us to access all of the elements in the Set with ease.

Exercise(s):

1. Make an integer set, and copy the contents of the stack to another set using loops. (Note: how is this different from the exercises with Stacks and Queues?)

2. Make 2 sets, and write a program to construct a new set which is the union of the first two.

3. Make 2 sets, and write a program to construct a new set which is the difference of the first two.

A Neat Addendum:

In Java, Sets are based on the "Mathematical Set" type, which arises from Set Theory in Mathematics. For example, in Exercise 2 and 3, we used the terms "union" and "difference". The union of 2 sets (A and B) is simply the set that contains all elements of A and B. The difference is the set that contains only the commonalities of A and B. Look out for Set Theory in our Math Courses!