This is the lecture note of CS61B - Lecture 11.
Lists and Sets in Java
In real world, we won't built the data structures such as LinkedList
, AList
, Deque
etc. from scratch. Instead, we will use the Java's built-in data structures directly.
In this part, let's see Java's built-in data structures.
Lists
Java provides a built-in List interface, and several implementations such as ArrayList.
1 | import java.util.List; |
Sets
Another handy data structure is Set.
1 | import java.util.Set; |
For the rest of the blog, we will talk about how to implement our own Set called ArraySet.
Basic ArraySet
1 | public class ArraySet<T> { |
Exceptions
The above code has a subtle bug. See the comment in main
method.
Since the bug, if we uncomment and run the above code, it will crash and break the normal flow of control. And the compiler will throw the exception.
We can throw our own exceptions, too.
1 | public void add(T x) { |
Iterable
Our ArraySet doesn't support enhanced for loop, that means it isn't iterable.
Before trying to make our ArraySet supports enhanced for loop, firstly, let's try to use an alternative way to iterate.
Actually, the enhanced for loop is just shorthand of this ugly while loop. The extra you need to do is declaring that public class ArraySet<T> implements Iterable<T>
1 | import java.util.Iterator; |
Object Methods:
#1: toString
1 | import java.util.Iterator; |
#2: equals
As mentioned before, ==
and .equals()
behave differently.
==
compares the bits. For reference, it means "referencing the same object"
1 | import java.util.Iterator; |
Extra: Better toString and ArraySet.of
1 | import java.util.Iterator; |