12.1 Lists and Sets in Java
Last updated
Last updated
In this section, we will learn about how to use Java's built-in List
and Set
data structures as well as build our own ArraySet
.
In this course, we've already built two kinds of lists: AList
and SLList
. We also built an interface List61B
to enforce specific list methods AList
and SLList
had to implement. You can find the code at the following links:
This is how we might use List61B
type:
We built a list from scratch, but Java provides a built-in List
interface and several implementations, e.g. ArrayList
. Remember, since List
is an interface we can't instantiate it! We must instantiate one of its implementations.
To access this, we can use the full name ('canonical name') of classes/interfaces:
However, this is a bit verbose. Instead, we can import java libraries:
Sets are a collection of unique elements - you can only have one copy of each element. Unlike Lists, there is also no sense of order: you can't index into a set, nor can you control where each element is inserted into the set.
Java has the Set
interface along with implementations, e.g. HashSet
. Remember to import them if you don't want to use the full name!
Example use:
In python, we simply call set()
. To check for contains
we don't use a method but the keyword in
. Here's an example:
Our goal is to make our own set, ArraySet
, with the following methods:
add(value)
: add the value to the set if not already present
contains(value)
: check to see if ArraySet contains the key
size()
: return number of values
If you would like to try it yourself, find 'Do It Yourself' ArraySet starter code
. In the lecture clip below, Professor Hug goes develops the solution: