12.1 Lists and Sets in Java
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
.
Getting Started
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:
Lists in Real Java Code
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
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 Sets
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:
Python Equivalent
In python, we simply call set()
. To check for contains
we don't use a method but the keyword in
. Here's an example:
DIY: ArraySet
Our goal is to make our own set, ArraySet
, with the following methods:
add(value)
: add the value to the set if not already presentcontains(value)
: check to see if ArraySet contains the keysize()
: return number of values
If you would like to try it yourself, find 'Do It Yourself' ArraySet starter code
here. In the lecture clip below, Professor Hug goes develops the solution:
Last updated