Collections: Lists, ArrayLists, Sets

What we’ll cover

What is a Collection?

Collection Interface

public interface Collection<E> extends Iterable<E> {
    boolean add(E element);
    boolean addAll(Collection<? extends E> collection);
    void clear();
    boolean contains(Object object);
    boolean containsAll(Collection<?> collection);
    void foreach(Consumer<E> consumer);
    boolean isEmpty();
    Iterator<E> iterator();
    boolean remove(Object object);
    boolean removeAll(Collection<?> collection);
    boolean retainAll(Collection<?> collection);
    int size();
    Object[] toArray();
    <T> T[] toArray(T[] array);
}

What is a List?

List Interface

public interface List<E> extends Collection<E> {
  int lastIndexOf(Object object);
  int indexOf(Object object);
  E set(int index, E object);
  List<E> sub(int startingIndex, int endingIndex);
}

ArrayList

Unmodifiable List

public void demo() {
  String[] array = {"The", "Quick", "Brown", "Fox"};
  List<String> unmodifiableList = Arrays.asList(array);
  unmodifiableList.add("Jumps"); // throws Exception
}

Output

java.lang.UnsupportedOperationException

Converting Array to ArrayList

public void demo() {
  String[] array = {"The", "Quick", "Brown", "Fox"};
  List<String> unmodifiableList = Arrays.asList(array);
  List<String> arrayList = new ArrayList<>(unmodifiableList);
  System.out.println(arrayList);
}

Output

[The, Quick, Brown, Fox]
public void demo() {
  String[] phrase = {"The", "Quick", "Brown", "Fox"};
  List<String> list = new ArrayList<>();
  for(String word : phrase) {
    list.add(word);
  }
}
public void demo() {
  String[] phrase = {"The", "Quick", "Brown", "Fox"};
  List<String> list = new ArrayList<>();
  list.foreach(word -> list.add(word));
}

Set Interface

Sets

HashSet sorts elements in hash order (fast, not predictable)
TreeSet sorts elements in ascending sorted order
LinkedHashSet provides insertion-order access to elements
EnumSet Optimized set for holding enum instances
BitSet Optimized for storing sequences of bits

HashSet

HashSet example

public void test() {
    String[] words = {"John", "Charles", "Cutler", "Tuskegee"};
    Set<String> set = new HashSet<>(Arrays.asList(words));
    System.out.println(set);
}

Output

[Charles, Tuskegee, John, Cutler]

TreeSet

TreeSet example

public void test() {
    String[] words = {"John", "Charles", "Cutler", "Tuskegee"};
    Set<String> set = new TreeSet<>(Arrays.asList(words));
    System.out.println(set);
}

Output

[Charles, Cutler, John, Tuskegee]

LinkedHashSet

LinkedHashSet example

public void test() {
    String[] words = {"John", "Charles", "Cutler", "Tuskegee"};
    Set<String> set = new LinkedHashSet<>(Arrays.asList(words));
    System.out.println(set);
}

Output

[John, Charles, Cutler, Tuskegee]