# Sets

{% hint style="warning" %}
This page is from my original notes and is not up to the latest quality standards. Read with care or [help make it better!](https://github.com/64bitpandas/cs61b-notes/pulls)
{% endhint %}

## Basics

A Set stores a collection of values with **no duplicates.** Sets have no inherent order, so you can't rely on expecting any value to come before any other value when iterating through them.

Some set functions include:

* `add(T x)`
* `contains(T x)`
* `size()`

## ArraySet

An ArraySet is an array-based solution to a set implementation.&#x20;

* Objects get added to an array that gets [resized](/asymptotics/amortization.md) when it's too full.
* In order to allow for iteration, we can use one of two methods:
  * One method is to use **iterators** which work very similarly to Python iterators:

    ```java
    Iterator<Integer> seer = set.iterator();
    while (seer.hasNext()) {
      System.out.println(seer.next());
    }
    ```
  * Another method is to implement the `Iterator` and `Iterable` interface.
    * Iterator must implement `hasNext()` and `next()` methods
    * Requires generic type
    * Iterable must implement `iterator()` method which returns the Iterable object
    * Allows usage of for/foreach loops


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs61b.bencuan.me/abstract-data-types/collections/sets.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
