Exceptions, Iterators, Object Methods
Lists
Java provides us a built-in List interface and several implementations.
java.util.List<Integer> L = new java.util.ArrayList<>();We could import the packages to make the code more simple.
import java.util.List;
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
List<Integer> L = new ArrayList<>();
L.add(5);
L.add(10);
System.out.println(L);
}
}Sets
Sets are a collection of unique elements, which means that you can only have one copy of each element. There is also no sense of order.
ArraySet
Our goal is to make our own set with ArrayList we built before, which has 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
Here's our code.
Exceptions
When we add null to our ArraySet, the program will crash since we are calling null.equals(x) and will throw a NullPointerException.
However, we could manually throw an exception IllegalArgumentException by updating the add method.
Iterations
We could use enhanced loop in Java's HashSet:
The code above is equal to the following ugly implementaion.
If we want to do the same (ugly version of enhanced loop) with our own ArraySet, we have to implement the Iterator interface.
However, if we want to let our class support enhanced for loop, we have to implement Iterable interface.
toString
If we want to print out the whole class, we have to override toString method, or we will only get the name and the address of the object.
Here's an enhanced version utilizing the StringBuilder which is more efficient.
equals
In order to check whether a given object is equal to another object, we have to implement the equals method, since == will only compare the memory address.
Last updated